[并查集] D. 0-1-Tree

本文介绍了一种在树形结构中使用并查集算法解决特定路径计数问题的方法。具体而言,针对给定的带权无向连通无环图(即树),文章详细阐述了如何通过并查集维护节点间的最大联通块,进而高效计算出所有满足先0后1边顺序的顶点对数量。该算法巧妙地利用了树的特性,确保了计算的准确性和效率。

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

You are given a tree (an undirected connected acyclic graph) consisting of nn vertices and n−1n−1 edges. A number is written on each edge, each number is either 00 (let's call such edges 00-edges) or 11 (those are 11-edges).

Let's call an ordered pair of vertices (x,y)(x,y) (x≠yx≠y) valid if, while traversing the simple path from xx to yy, we never go through a 00-edge after going through a 11-edge. Your task is to calculate the number of valid pairs in the tree.

Input

The first line contains one integer nn (2≤n≤2000002≤n≤200000) — the number of vertices in the tree.

Then n−1n−1 lines follow, each denoting an edge of the tree. Each edge is represented by three integers xixi, yiyi and cici (1≤xi,yi≤n1≤xi,yi≤n, 0≤ci≤10≤ci≤1, xi≠yixi≠yi) — the vertices connected by this edge and the number written on it, respectively.

It is guaranteed that the given edges form a tree.

Output

Print one integer — the number of valid pairs of vertices.

 题意:给定一颗树, 求满足任意两点间先0后1路径条数


思路:如图所示

以1为当前节点

由树的性质则必有当前节点的1最大联通块为1路径条数 sa (3)

当前节点的0最大联通块为0路径条数 sb (3)

则有通过当前节点且符合题意的路径有 sa * sb - 1(减去当前节点自身的重复统计)

所以用并查集维护节点的最大联通块计算答案即可


代码:

/*
    Zeolim - An AC a day keeps the bug away
*/

//#pragma GCC optimize(2)
#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>
#include <cctype>
#include <string>
#include <cstring>
#include <algorithm>
#include <stack>
#include <queue>
#include <set>
#include <sstream>
#include <map>
#include <ctime>
#include <vector>
#include <fstream>
#include <list>
#include <iomanip>
#include <numeric>
using namespace std;
typedef long long ll;
typedef long double ld;
const int INF = 0x3f3f3f3f;
const ld PI = acos(-1.0);
const ld E = exp(1.0);

const int MAXN = 1e6 + 10;

ll fa[MAXN], fb[MAXN], vla[MAXN], vlb[MAXN];

int findfa(int x)
{
    return x == fa[x] ? x : fa[x] = findfa(fa[x]);
}

int findfb(int x)
{
    return x == fb[x] ? x : fb[x] = findfb(fb[x]);
}

int main()
{
    //ios::sync_with_stdio(false);
    //cin.tie(0);     cout.tie(0);
    //freopen("D://test.in", "r", stdin);
    //freopen("D://test.out", "w", stdout);

    int n;

    cin >> n;

    for(int i = 0; i <= n; ++i)
    {
        fa[i] = fb[i] = i;
        vla[i] = vlb[i] = (ll)1;
    }

    for(int i = 1; i < n; ++i)
    {
        int a, b, val;

        cin >> a >> b >> val;

        if(val == 1)
        {
            int p = findfa(a), q = findfa(b);
            fa[p] = q;
            vla[q] += vla[p];
        }

        else
        {
            int p = findfb(a), q = findfb(b);
            fb[p] = q;
            vlb[q] += vlb[p];
        }
    }

    ll ans = 0;

    for(int i = 1; i <= n; ++i)
    {
    	int p = findfa(i), q = findfb(i);
        ll tsum = vla[p] * vlb[q] - 1ll;
        ans += (tsum);
    }   

    cout << ans << '\n';
    
    return 0;
}

 

root@sw:~/Serve/vscode# chmod 777 uninstall.sh root@sw:~/Serve/vscode# ./uninstall.sh Reading package lists... Done Building dependency tree... Done Reading state information... Done No apt package "code", but there is a snap with that name. Try "snap install code" E: Unable to locate package code Reading package lists... Done Building dependency tree... Done Reading state information... Done The following packages will be REMOVED: libauthen-sasl-perl* libclone-perl* libdata-dump-perl* libencode-locale-perl* libfile-basedir-perl* libfile-desktopentry-perl* libfile-listing-perl* libfile-mimeinfo-perl* libfont-afm-perl* libhtml-form-perl* libhtml-format-perl* libhtml-parser-perl* libhtml-tagset-perl* libhtml-tree-perl* libhttp-cookies-perl* libhttp-daemon-perl* libhttp-date-perl* libhttp-message-perl* libhttp-negotiate-perl* libio-html-perl* libio-socket-ssl-perl* libio-stringy-perl* libipc-system-simple-perl* liblwp-mediatypes-perl* liblwp-protocol-https-perl* libmailtools-perl* libnet-dbus-perl* libnet-http-perl* libnet-smtp-ssl-perl* libnet-ssleay-perl* libproxychains3* libtie-ixhash-perl* libtimedate-perl* libtry-tiny-perl* liburi-perl* libwww-perl* libwww-robotrules-perl* libx11-protocol-perl* libxml-parser-perl* libxml-twig-perl* libxml-xpathengine-perl* mesa-utils-bin* perl-openssl-defaults* xdg-utils* 0 upgraded, 0 newly installed, 44 to remove and 26 not upgraded. After this operation, 8,426 kB disk space will be freed. (Reading database ... 110336 files and directories currently installed.) Removing libauthen-sasl-perl (2.1600-1.1) ... Removing libclone-perl (0.45-1build3) ... Removing libdata-dump-perl (1.25-1) ... Removing libnet-dbus-perl (1.2.0-1build3) ... Removing libxml-twig-perl (1:3.52-1) ... Removing libxml-parser-perl:amd64 (2.46-3build1) ... Removing libhttp-daemon-perl (6.13-1ubuntu0.1) ... Removing libfile-mimeinfo-perl (0.31-1) ... Removing libfile-desktopentry-perl (0.22-2) ... Removing libfile-basedir-perl (0.09-1) ... Removing libhtml-format-perl (2.12-1.1) ... Removing libfont-afm-perl (1.20-3) ... Removing libhtml-form-perl (6.07-1) ... Removing libmailtools-perl (2.21-1) ... Removing libnet-smtp-ssl-perl (1.04-1) ... Removing libio-stringy-perl (2.111-3) ... Removing libipc-system-simple-perl (1.30-1) ... Removing libproxychains3:amd64 (3.1-9) ... Removing libtie-ixhash-perl (1.23-2.1) ... Removing libx11-protocol-perl (0.56-7.1) ... Removing libxml-xpathengine-perl (0.14-1) ... Removing mesa-utils-bin:amd64 (8.4.0-1ubuntu1) ... Removing xdg-utils (1.1.3-4.1ubuntu3~22.04.1) ... Removing liblwp-protocol-https-perl (6.10-1) ... Removing libwww-perl (6.61-1) ... Removing libfile-listing-perl (6.14-1) ... Removing libhtml-tree-perl (5.07-2) ... Removing libhtml-parser-perl:amd64 (3.76-1build2) ... Removing libhtml-tagset-perl (3.20-4) ... Removing libhttp-cookies-perl (6.10-1) ... Removing libhttp-negotiate-perl (6.01-1) ... Removing libio-socket-ssl-perl (2.074-2) ... Removing libnet-http-perl (6.22-1) ... Removing libnet-ssleay-perl:amd64 (1.92-1build2) ... Removing libtry-tiny-perl (0.31-1) ... Removing libwww-robotrules-perl (6.02-1) ... Removing perl-openssl-defaults:amd64 (5build2) ... Removing libhttp-message-perl (6.36-1) ... Removing libencode-locale-perl (1.05-1.1) ... Removing libhttp-date-perl (6.05-1) ... Removing libio-html-perl (1.004-2) ... Removing liblwp-mediatypes-perl (6.04-1) ... Removing libtimedate-perl (2.3300-2) ... Removing liburi-perl (5.10-1) ... Processing triggers for man-db (2.10.2-1) ... Processing triggers for libc-bin (2.35-0ubuntu3.9) ... Hit:1 http://mirrors.cloud.aliyuncs.com/ubuntu jammy InRelease Get:2 http://mirrors.cloud.aliyuncs.com/ubuntu jammy-updates InRelease [128 kB] Hit:3 http://mirrors.cloud.aliyuncs.com/ubuntu jammy-backports InRelease Get:4 http://mirrors.cloud.aliyuncs.com/ubuntu jammy-security InRelease [129 kB] Ign:5 https://download.docker.com/linux/ubuntu jammy InRelease Hit:5 https://download.docker.com/linux/ubuntu jammy InRelease Hit:6 https://packages.emqx.com/emqx/emqx/ubuntu jammy InRelease Fetched 257 kB in 3s (94.1 kB/s) Reading package lists... Done Building dependency tree... Done Reading state information... Done 26 packages can be upgraded. Run 'apt list --upgradable' to see them. Warning: apt-key is deprecated. Manage keyring files in trusted.gpg.d instead (see apt-key(8)). 验证结果: [成功] VSCode二进制文件已移除 [警告] 存在残留进程 root@sw:~/Serve/vscode# 怎么解决?
最新发布
05-13
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值