带权并查集

带权并查集

例:POJ1182食物链

动物王国中有三类动物A,B,C,这三类动物的食物链构成了有趣的环形。A吃B, B吃C,C吃A。 
现有N个动物,以1-N编号。每个动物都是A,B,C中的一种,但是我们并不知道它到底是哪一种。
有人用两种说法对这N个动物所构成的食物链关系进行描述: 
第一种说法是"1 X Y",表示X和Y是同类。 
第二种说法是"2 X Y",表示X吃Y。 
此人对N个动物,用上述两种说法,一句接一句地说出K句话,这K句话有的是真的,有的是假的。当一句话满足下列三条之一时,这句话就是假话,否则就是真话。 
1) 当前的话与前面的某些真的话冲突,就是假话; 
2) 当前的话中X或Y比N大,就是假话; 
3) 当前的话表示X吃X,就是假话。 
你的任务是根据给定的N(1 <= N <= 50,000)和K句话(0 <= K <= 100,000),输出假话的总数。 

Input

第一行是两个整数N和K,以一个空格分隔。 
以下K行每行是三个正整数 D,X,Y,两数之间用一个空格隔开,其中D表示说法的种类。 
若D=1,则表示X和Y是同类。 
若D=2,则表示X吃Y。

Output

只有一个整数,表示假话的数目。

Sample Input

100 7
1 101 1 
2 1 2
2 2 3 
2 3 3 
1 1 3 
2 3 1 
1 5 5

Sample Output

3

详细注解:https://blog.youkuaiyun.com/qq_29660153/article/details/68076314

相似题目:Bug's Life hdu-1829

Problem Description

Background 
Professor Hopper is researching the sexual behavior of a rare species of bugs. He assumes that they feature two different genders and that they only interact with bugs of the opposite gender. In his experiment, individual bugs and their interactions were easy to identify, because numbers were printed on their backs. 

Problem 
Given a list of bug interactions, decide whether the experiment supports his assumption of two genders with no homosexual bugs or if it contains some bug interactions that falsify it.

Input

The first line of the input contains the number of scenarios. Each scenario starts with one line giving the number of bugs (at least one, and up to 2000) and the number of interactions (up to 1000000) separated by a single space. In the following lines, each interaction is given in the form of two distinct bug numbers separated by a single space. Bugs are numbered consecutively starting from one.

Output

The output for every scenario is a line containing "Scenario #i:", where i is the number of the scenario starting at 1, followed by one line saying either "No suspicious bugs found!" if the experiment is consistent with his assumption about the bugs' sexual behavior, or "Suspicious bugs found!" if Professor Hopper's assumption is definitely wrong.

Sample Input

2

3 3

1 2

2 3

1 3

4 2

1 2

3 4

Sample Output

Scenario #1:

Suspicious bugs found!

Scenario #2:

No suspicious bugs found!

Hint

Huge input,scanf is recommended.

题意大概是随便给你一堆虫子,拿出来两个交配要是两个为同性就是出bug了!

注意输入输出!

当前点与根节点的关系可以看成向量

如图:

当ra != rb 时进行虚线的变化, srb指b与rb之间的关系,sra同srb

具体代码如下:

#include <iostream>
#include <cstdio>
using namespace std;

int root[2005], sroot[2005];
int rfind(int a, int &ans)
{
    ans = 0;
    while(root[a] != a)
    {
        ans = (ans + sroot[a]) % 2;
        a = root[a];
    }
    return a;
}
int main()
{
    int cn, T;
    scanf("%d", &T);
    for(cn = 1; cn <= T; cn++)
    {
        int m, n, i, ans = 0;
        scanf("%d%d",&m, &n);
        for(i = 0; i <= m; i++)
        {
            root[i] = i;
            sroot[i] = 0;
        }
        for(i = 0; i < n; i++)
        {
            int a, b;
            scanf("%d%d",&a, &b);
            int ra, rb, sra, srb;
            ra = rfind(a, sra);
            rb = rfind(b, srb);
            if(a > m || a < 1 || b > m || b < 1)
            {
                ans++;
                continue;
            }
            if(ans == 0)
            {
                if(ra != rb)
                {
                    root[rb] = ra;
                    sroot[rb] = (sra - srb + 1) % 2;
                }
                else
                {
                    if(sra == srb)
                    {
                        ans++;
                    }
                }
            }
        }
        if(cn != 1)
            cout << endl;
        cout << "Scenario #" << cn << ":" << endl;
        if(ans != 0)
        {
            cout << "Suspicious bugs found!" << endl;
        }
        else
        {
            cout << "No suspicious bugs found!" << endl;
        }
    }
    return 0;
}

另一道带权并查集的题,或者说另一种思想。。。。。。

poj:1988

Cube Stacking

Time Limit: 2000MS Memory Limit: 30000K
Total Submissions: 28794 Accepted: 10105
Case Time Limit: 1000MS

Description

Farmer John and Betsy are playing a game with N (1 <= N <= 30,000)identical cubes labeled 1 through N. They start with N stacks, each containing a single cube. Farmer John asks Betsy to perform P (1<= P <= 100,000) operation. There are two types of operations: 
moves and counts. 
* In a move operation, Farmer John asks Bessie to move the stack containing cube X on top of the stack containing cube Y. 
* In a count operation, Farmer John asks Bessie to count the number of cubes on the stack with cube X that are under the cube X and report that value. 

Write a program that can verify the results of the game. 

Input

* Line 1: A single integer, P 

* Lines 2..P+1: Each of these lines describes a legal operation. Line 2 describes the first operation, etc. Each line begins with a 'M' for a move operation or a 'C' for a count operation. For move operations, the line also contains two integers: X and Y.For count operations, the line also contains a single integer: X. 

Note that the value for N does not appear in the input file. No move operation will request a move a stack onto itself. 

Output

Print the output from each of the count operations in the same order as the input file. 

Sample Input

6
M 1 6
C 1
M 2 4
M 2 6
C 3
C 4

Sample Output

1
0
2

大致意思就是有一堆箱子,有两种操作,一种是把a以及a下面的箱子放到b上,另一种就是查询b下面有多少箱子!

这道题借鉴了网上的一些代码,其中让我觉得巧妙的是,root【i】数组被赋值为-1,每一次合并就将root【a】+root【b】这样就得到了a下面有-n(注意是负的!)个箱子,最后结果用根减去当前的在减一就是答案了。

代码如下:

#include <iostream>
#include <cstdio>
using namespace std;

int root[30005], sroot[30005];
int getroot(int a)
{
    if(root[a] < 0)
    {
        return a;
    }
    int p = root[a];
    root[a] = getroot(p);
    sroot[a] += sroot[p];
    return root[a];
}
int main()
{
    int p, i;
    for(i = 0; i < 30005; i++)
    {
        root[i] = -1;
        sroot[i] = 0;
    }
    cin >> p;
    while(p--)
    {
        int a, b;
        char c;
        getchar();
        scanf("%c",&c);
        if(c == 'C')
        {
            scanf("%d", &a);
            int ra = getroot(a), ans;
            ans = (-root[ra]) - sroot[a] - 1;
            cout << ans << endl;

        }else if(c == 'M')
        {
            scanf("%d%d", &a, &b);
            int ra, rb;
            rb = getroot(b);
            ra = getroot(a);
            if(ra != rb)
            {
                sroot[rb] = -root[ra];
                root[ra] += root[rb];
                root[rb] = ra;
            }
        }
    }
    return 0;
}

 

### 带权并查集的数据结构实现模板 带权并查集是一种扩展的并查集数据结构,用于处理带有权重关系的问题。通过引入额外的信息来记录集合之间的相对权重差异,可以在解决一些复杂问题时提供更强大的功能。 以下是基于 Python 的带权并查集实现模板: #### 代码示例 ```python class WeightedUnionFind: def __init__(self, n): self.parent = list(range(n)) # 初始化父节点数组 self.rank = [0] * n # 初始化秩(高度) self.weight = [0] * n # 权重差值初始化为0 # 查找操作,路径压缩优化 def find(self, x): if self.parent[x] != x: root_x = self.find(self.parent[x]) self.weight[x] += self.weight[self.parent[x]] # 更新权重 self.parent[x] = root_x # 路径压缩 return self.parent[x] # 合并操作,按秩合并优化 def union(self, x, y, w): rx, ry = self.find(x), self.find(y) # 如果两个节点已经在同一个集合中,则无需再合并 if rx == ry: return # 计算y相对于x的权重调整量 diff = w + self.weight[x] - self.weight[y] # 按秩合并 if self.rank[rx] < self.rank[ry]: self.parent[rx] = ry self.weight[rx] = -diff elif self.rank[rx] > self.rank[ry]: self.parent[ry] = rx self.weight[ry] = diff else: self.parent[ry] = rx self.weight[ry] = diff self.rank[rx] += 1 # 查询两点间的实际权重差 def get_weight_diff(self, x, y): if self.find(x) != self.find(y): # 若不在同一集合则无法比较 return None return self.weight[y] - self.weight[x] ``` 上述代码实现了带权并查集的核心功能,包括 `find` 方法(支持路径压缩)、`union` 方法(支持按秩合并以及权重更新)和查询两点间权重差的功能[^1]。 --- #### 使用说明 - **初始化**:创建一个大小为 `n` 的对象实例,表示有 `n` 个独立节点。 - **查找根节点 (`find`):** - 返回当前节点所属集合的根节点,并在过程中应用路径压缩以提高效率。 - 同时动态维护每条路径上的权重累加值。 - **合并两棵树 (`union`):** - 将两个不同集合合并成一个新的集合。 - 需要传入参数 `w` 表示从节点 `x` 到节点 `y` 的权重变化。 - 应用了按秩合并策略以减少树的高度。 - **计算权重差 (`get_weight_diff`):** - 给定两个节点 `x` 和 `y`,返回它们之间的实际权重差。 - 如果两者不属于同一个集合,则返回 `None`。 这种设计使得带权并查集能够高效地管理复杂的带权图结构,在最小生成树等问题中有广泛应用场景[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值