1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122
| #include<iostream> #include<cstring> #include<vector> #include<queue> #include<string> #include<algorithm> #include<cmath> #include<cstdio> #include<set> #include<map> #include<bitset> #define put putchar #define ls(k) (k << 1) #define rs(k) (k << 1 | 1) #define LL long long #define int long long
using namespace std;
const int N = 2e4 + 10, M = N << 1;
int n, ans, ans2; int dis[N], sz[N], mx[N], root, q[3], cnt; bool st[N];
int h[N], idx; struct Edge { int to, ne, w; } e[M];
template<class T> inline void read(T &x) { T res = 0, f = 1; char c = getchar(); while(! isdigit(c)) { if(c == '-') f = -1; c = getchar(); } while(isdigit(c)) res = (res << 1) + (res << 3) + c - 48, c = getchar(); x = res * f; return ; } template<class T, class ...T1> inline void read(T &x, T1 &...x1) { read(x), read(x1...); return ; } template<class T> inline void write(T x) { if(x < 0) x = -x, put('-'); if(x > 9) write(x / 10); put(x % 10 + 48); return ; } template<> inline void write(char x) { put(x); return ; } template<class T, class ...T1> inline void write(T x, T1 ...x1) { write(x),write(x1...); return ; }
void add(int a, int b, int c) { e[idx] = {b, h[a], c}, h[a] = idx ++; } void get_rt(int u, int fa, int tot) { sz[u] = 1, mx[u] = 0; for(int i = h[u]; ~i; i = e[i].ne) { int v = e[i].to; if(v == fa || st[v]) continue; get_rt(v, u, tot); mx[u] = max(mx[u], sz[v]), sz[u] += sz[v]; } mx[u] = max(mx[u], tot - sz[u]); if(mx[u] < mx[root]) root = u; return ; } void get_dis(int u, int fa, int d) { dis[u] = d % 3, ++ q[dis[u]]; for(int i = h[u]; ~i; i = e[i].ne) { int v = e[i].to; if(v == fa || st[v]) continue; get_dis(v, u, d + e[i].w); } return ; } int calc(int u, int d) { q[0] = q[1] = q[2] = 0, dis[u] = d; get_dis(u, 0, d); return q[0] * q[0] + q[1] * q[2] * 2; } void solve(int u) { ans += calc(u, 0); st[u] = true; for(int i = h[u]; ~i; i = e[i].ne) { int v = e[i].to; if(st[v]) continue; ans -= calc(v, e[i].w); root = 0, get_rt(v, 0, sz[v]); solve(root); } return ; } int gcd(int a, int b) { return b ? gcd(b, a % b) : a; }
signed main() { read(n); memset(h, -1, sizeof h); mx[0] = n, ans2 = n * n; for(int i = 1, u, v, w; i < n; ++ i) read(u, v, w), add(u, v, w), add(v, u, w); get_rt(1, 0, n); solve(1); int g = gcd(ans, ans2); ans /= g, ans2 /= g; write(ans, '/', ans2); return 0; }
|