传送门
题目描述
补一个题解
给定一棵 nn 个点的边权为
0
0
0 或
1
1
1 的树,一条合法的路径
(
x
,
y
)
(
x
≠
y
)
(x,y)(x\neq y)
(x,y)(x=y)满足,从
x
x
x 走到
y
y
y,一旦经过边权为
1
1
1 的边,就不能再经过边权为
0
0
0 的边。求有多少路径满足条件?
分析
我们去维护两个块,第一个块是哪些点可以通过 0 0 0到达 i i i点,第二个块是哪些点可以通过 1 1 1到达 i i i点,然后用带权并查集维护一下即可
代码
#pragma GCC optimize(3)
#include <bits/stdc++.h>
#define debug(x) cout<<#x<<":"<<x<<endl;
#define dl(x) printf("%lld\n",x);
#define di(x) printf("%d\n",x);
#define _CRT_SECURE_NO_WARNINGS
#define pb push_back
#define mp make_pair
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
#define SZ(x) ((int)(x).size())
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const int N = 2e5 + 10;
const ll mod = 1000000007;
const double eps = 1e-9;
const double PI = acos(-1);
template<typename T>inline void read(T &a) {
char c = getchar(); T x = 0, f = 1; while (!isdigit(c)) {if (c == '-')f = -1; c = getchar();}
while (isdigit(c)) {x = (x << 1) + (x << 3) + c - '0'; c = getchar();} a = f * x;
}
int gcd(int a, int b) {return (b > 0) ? gcd(b, a % b) : a;}
int q[3][N];
ll sz[3][N];
int n;
int find(int x[],int a){
if(a != x[a]) x[a] = find(x,a[x]);
return x[a];
}
void merge(int x[],ll y[],int a,int b){
a = find(x,a),b = find(x,b);
if(a != b){
x[a] = b;
y[b] += y[a];
}
}
int main() {
read(n);
for(int i = 1;i <= n;i++){
q[0][i] = q[1][i] = i;
sz[0][i] = sz[1][i] = 1;
}
for(int i = 1;i < n;i++){
int x,y,z;
read(x),read(y),read(z);
merge(q[z],sz[z],x,y);
}
ll ans = 0;
for(int i = 1;i <= n;i++) ans += sz[0][find(q[0],i)] * sz[1][find(q[1],i)] - 1;
dl(ans);
return 0;
}
/**
* ┏┓ ┏┓+ +
* ┏┛┻━━━┛┻┓ + +
* ┃ ┃
* ┃ ━ ┃ ++ + + +
* ████━████+
* ◥██◤ ◥██◤ +
* ┃ ┻ ┃
* ┃ ┃ + +
* ┗━┓ ┏━┛
* ┃ ┃ + + + +Code is far away from
* ┃ ┃ + bug with the animal protecting
* ┃ ┗━━━┓ 神兽保佑,代码无bug
* ┃ ┣┓
* ┃ ┏┛
* ┗┓┓┏━┳┓┏┛ + + + +
* ┃┫┫ ┃┫┫
* ┗┻┛ ┗┻┛+ + + +
*/