# bzoj3697 采药人的路径

#### Input

$1$ 行包含一个整数 $N$

7
1 2 0
3 1 1
2 4 0
5 2 0
6 3 1
5 7 1

1

#### Solution

$f[i][0...1]$ 表示当前子树不存在/存在休息站的长度为 $i$ 路径数目。 $g[i][0...1]$ 表示之前访问过的子树不存在/存在休息站的长度为 $i$ 路径数目。

#include<bits/stdc++.h>
using namespace std;

#define N 200005
#define rep(i, a, b) for (int i = a; i <= b; i++)
#define drp(i, a, b) for (int i = a; i >= b; i--)
#define fech(i, x) for (int i = 0; i < x.size(); i++)
#define ll long long

int x = 0, flag = 1; char ch = getchar(); while (!isdigit(ch)) { if (!(ch ^ '-')) flag = -1; ch = getchar(); }
while (isdigit(ch)) x = (x << 1) + (x << 3) + ch - '0', ch = getchar(); return x * flag;
}

inline void write(int x) {
if (!x) { putchar('0'); return; } if (x < 0) putchar('-'), x = -x;
char buf[20] = ""; int top = 0; while (x) buf[++top] = x % 10 + '0', x /= 10; while (top) putchar(buf[top--]);
}

int n;
struct edgeType { int u, v, w; }eg[N]; int tot;
#define getEg edgeType e = eg[g[u][i]]
vector<int> g[N];
bool vis[N];
int Size[N], mx[N], sum, root, mxDep;
int dis[N], dep[N], t[N];
ll ans, F[N][2], G[N][2];

void getRoot(int u, int fa) {
Size[u] = 1; mx[u] = 0;
fech(i, g[u]) {
getEg; if (!(e.v ^ fa) || vis[e.v]) continue;
getRoot(e.v, u); Size[u] += Size[e.v], mx[u] = max(mx[u], Size[e.v]);
}
mx[u] = max(mx[u], sum - Size[u]);
if (mx[root] > mx[u]) root = u;
}

void calcDis(int u, int fa) {
mxDep = max(mxDep, dep[u]);
F[dis[u]][(bool)t[dis[u]]]++; t[dis[u]]++;
fech(i, g[u]) {
getEg; if (!(e.v ^ fa) || vis[e.v]) continue;
dis[e.v] = dis[u] + e.w, dep[e.v] = dep[u] + 1; calcDis(e.v, u);
}
t[dis[u]]--;
}

void solve(int u) {
int mx = 0; vis[u] = 1; G[n][0] = 1;
fech(i, g[u]) {
getEg; if (vis[e.v]) continue;
dep[e.v] = 1; dis[e.v] = e.w + n; mxDep = 1; calcDis(e.v, 0); mx = max(mx, mxDep);
ans += (G[n][0] - 1) * F[n][0];
rep(j, -mxDep, mxDep)
ans += G[n - j][1] * F[n + j][1] + G[n - j][0] * F[n + j][1] + G[n - j][1] * F[n + j][0];
rep(j, n - mxDep, n + mxDep) rep(k, 0, 1) G[j][k] += F[j][k], F[j][k] = 0;
}
rep(i, n - mx, n + mx) rep(j, 0, 1) G[i][j] = 0;
fech(i, g[u]) {
getEg; if (vis[e.v]) continue;
sum = Size[e.v]; root = 0; getRoot(e.v, 0); solve(root);
}
}

int main() {
n = read(); rep(i, 2, n) {