#include<bits/stdc++.h>
using namespace std;
#pragma GCC optimize ("Ofast")
#pragma GCC target ("avx2")
#define el << '\n'
#define nl cout << '\n'
#define cina(a,n) for (int i=0; i<n; i++) cin >> a[i]
#define ll long long
#define spc << ' '
#define forn(i,n) for (int i=0; i<n; i++)
#define forl(i,s,e) for (int i=s; i<e; i++)
#define MOD 1000000007
#define MOD2 998244353
#define pb push_back
#define ansyes cout << "YES\n"
#define ansno cout << "NO\n"
#define fi first
#define se second
#define pii pair<int,int>
#define pll pair<long long, long long>
int n;
vector<pair<int, bool>> acc[200000];
pll dp[200000];
ll tot=0;
void dfs1(int cn, int pn) {
dp[cn].fi = 1;
// if (acc[cn].size()>1) dp[cn].se = 1;
for (pair<int, bool> i : acc[cn]) {
if (i.fi == pn) continue;
// if (cn == 6) cout << i.fi el;
dfs1(i.fi, cn);
if (i.se) {
dp[cn].se += dp[i.fi].se;
dp[cn].se += dp[i.fi].fi;
}
else {
dp[cn].fi += dp[i.fi].fi;
}
}
return;
}
void reroot(int cr, int nr, bool ct) {
// if ()
if (!ct) {
dp[cr].fi -= dp[nr].fi;
dp[nr].fi += dp[cr].fi;
}
else {
dp[cr].se -= dp[nr].fi;
dp[cr].se -= dp[nr].se;
dp[nr].se += dp[cr].fi;
dp[nr].se += dp[cr].se;
}
return;
}
void dfs2(int cn, int pn, bool ct) {
tot += dp[cn].fi + dp[cn].se - 1;
// if (cn == 3) {
// forn(i,n) cout << dp[i].fi spc << dp[i].se el;
// }
for (pair<int, bool> i : acc[cn]) {
if (i.fi == pn) continue;
reroot(cn, i.fi, i.se);
dfs2(i.fi, cn, i.se);
}
if (pn != -1) reroot(cn, pn, ct);
}
int main() {
cin >> n;
forn(i,n-1) {
pair<int, bool> t1, t2; cin >> t1.fi >> t2.fi;
t1.fi--;
t2.fi--;
bool ct; cin >> ct;
if (ct==1) {
t1.se = true;
t2.se = true;
}
else {
t1.se = false;
t2.se = false;
}
acc[t1.fi].pb(t2);
acc[t2.fi].pb(t1);
}
dfs1(0, -1);
// forn(i,n) cout << dp[i].fi spc << dp[i].se el;
dfs2(0, -1, 0);
cout << tot el;
}
437. Path Sum III | 436. Find Right Interval |
435. Non-overlapping Intervals | 406. Queue Reconstruction by Height |
380. Insert Delete GetRandom O(1) | 332. Reconstruct Itinerary |
368. Largest Divisible Subset | 377. Combination Sum IV |
322. Coin Change | 307. Range Sum Query - Mutable |
287. Find the Duplicate Number | 279. Perfect Squares |
275. H-Index II | 274. H-Index |
260. Single Number III | 240. Search a 2D Matrix II |
238. Product of Array Except Self | 229. Majority Element II |
222. Count Complete Tree Nodes | 215. Kth Largest Element in an Array |
198. House Robber | 153. Find Minimum in Rotated Sorted Array |
150. Evaluate Reverse Polish Notation | 144. Binary Tree Preorder Traversal |
137. Single Number II | 130. Surrounded Regions |
129. Sum Root to Leaf Numbers | 120. Triangle |
102. Binary Tree Level Order Traversal | 96. Unique Binary Search Trees |