AcWing 240. 食物链(Weighted disjoint set union) Described by Java

A difficult problem is about weighted disjoint set union, to maintain another array distance[] to describe the distance from x to p[x].
And the problem. Problem


Like a tree , the distance from the leaves to root represents the category(0, 1, 2) and the upper can be surplus 3.
So the situations:
if handle is 1: to check if two number is in one category, if not, res++
if handle is 2: to check the category . Both need to be updated, complexity.
We can browse the code:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;

public class Main {
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static PrintWriter pw = new PrintWriter(System.out);
    static final int N = 50010;
    static int p[] = new int[N], d[] = new int[N], n, k;

    public static int find(int x) {
        if (p[x] != x) {
            int t = find(p[x]);
            d[x] += d[p[x]];
            p[x] = t;
        }
        return p[x];
    }

    public static void main(String[] rags) throws IOException {
        String[] s = br.readLine().split(" ");
        n = Integer.parseInt(s[0]);
        k = Integer.parseInt(s[1]);
        for (int i = 1; i <= n; i++) p[i] = i;
        int res = 0;
        while (k-- > 0) {
            String ss[] = br.readLine().split(" ");
            int t = Integer.parseInt(ss[0]);
            int x = Integer.parseInt(ss[1]);
            int y = Integer.parseInt(ss[2]);
            if (x > n || y > n) res++;
            else {
                int px = find(x), py = find(y);
                if (t == 1) {
                    if (px == py && (d[x] - d[y]) % 3 != 0) res++;
                    else {
                        if (px != py) {
                            p[px] = py;
                            d[px] = d[y] - d[x];
                        }
                    }
                } else {
                    if (px == py && (d[x] - 1 - d[y]) % 3 != 0) res++;
                    else {
                        if (px != py) {
                            p[px] = py;
                            d[px] = d[y] + 1 - d[x];
                        }
                    }
                }
            }
        }
        pw.println(res);
        pw.flush();
        br.close();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值