还是点分治

树上问题真有趣ovo,这道题统计模3为0的距离,可以把重心的子树分开统计,也可以一次性统计,然后容斥原理减掉重复的。。

其他的过程就是点分治的板子啦。

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define full(a, b) memset(a, b, sizeof a)
using namespace std;
typedef long long ll;
inline int lowbit(int x){ return x & (-x); }
inline int read(){
int X = 0, w = 0; char ch = 0;
while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
return w ? -X : X;
}
inline int gcd(int a, int b){ return a % b ? gcd(b, a % b) : b; }
inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
template<typename T>
inline T max(T x, T y, T z){ return max(max(x, y), z); }
template<typename T>
inline T min(T x, T y, T z){ return min(min(x, y), z); }
template<typename A, typename B, typename C>
inline A fpow(A x, B p, C lyd){
A ans = 1;
for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
return ans;
}
const int N = 50005;
int n, cnt, rt, ans, sum, res, head[N], size[N], r[3], cur[3], dis[N];
bool vis[N];
struct Edge{ int v, next, w; } edge[N<<1]; void addEdge(int a, int b, int c){
edge[cnt].v = b, edge[cnt].w = c, edge[cnt].next = head[a], head[a] = cnt ++;
} void dfs(int s, int fa){
int mp = 0;
size[s] = 1;
for(int i = head[s]; i != -1; i = edge[i].next){
int u = edge[i].v;
if(u == fa || vis[u]) continue;
dfs(u, s);
size[s] += size[u];
mp = max(mp, size[u]);
}
mp = max(mp, sum - size[s]);
if(mp < ans) ans = mp, rt = s;
} void getDis(int s, int fa){
res += r[(3 - dis[s]) % 3];
cur[dis[s]] ++;
for(int i = head[s]; i != -1; i = edge[i].next){
int u = edge[i].v;
if(u == fa || vis[u]) continue;
dis[u] = (dis[s] + edge[i].w) % 3;
getDis(u, s);
}
} void calc(int s){
r[0] = 1;
for(int i = head[s]; i != -1; i = edge[i].next){
int u = edge[i].v;
if(vis[u]) continue;
full(cur, 0);
dis[u] = edge[i].w % 3;
getDis(u, s);
for(int j = 0; j < 3; j ++) r[j] += cur[j];
}
full(r, 0);
} void solve(int s){
vis[s] = true, calc(s);
for(int i = head[s]; i != -1; i = edge[i].next){
int u = edge[i].v;
if(vis[u]) continue;
ans = INF, sum = size[u];
dfs(u, 0), solve(rt);
}
} int main(){ full(head, -1);
n = read();
for(int i = 0; i < n - 1; i ++){
int u = read(), v = read(), c = read() % 3;
addEdge(u, v, c), addEdge(v, u, c);
}
ans = INF, sum = n;
dfs(1, 0), solve(rt);
res = (res << 1) + n;
int t = gcd(res, n * n);
printf("%d/%d\n", res / t, n * n / t);
return 0;
}
05-04 03:28