题面
https://www.luogu.org/problem/P2634
题解
#include<cstdio> #include<iostream> #include<vector> using namespace std; vector<int> to[20500],len[20500]; int n; int dp[20500][3]; long long tot,ans; // len[x][i]+j+dis=0 dis=-j-len[x][i] // x+len void dfs(int x,int ff) { int i,l=to[x].size(); dp[x][0]=1; dp[x][1]=0; dp[x][2]=0; for (i=0;i<l;i++) if (to[x][i]!=ff) { dfs(to[x][i],x); ans+=dp[to[x][i]][(6-len[x][i])%3]*1LL*dp[x][0]; ans+=dp[to[x][i]][(5-len[x][i])%3]*1LL*dp[x][1]; ans+=dp[to[x][i]][(4-len[x][i])%3]*1LL*dp[x][2]; dp[x][len[x][i]]+=dp[to[x][i]][0]; dp[x][(1+len[x][i])%3]+=dp[to[x][i]][1]; dp[x][(2+len[x][i])%3]+=dp[to[x][i]][2]; } } long long gcd(long long x,long long y) { if (!y) return x; else return gcd(y,x%y); } int main(){ int i,u,v,l; scanf("%d",&n); tot=n*n; for (i=1;i<n;i++) { scanf("%d %d %d",&u,&v,&l); l%=3; to[u].push_back(v); len[u].push_back(l); to[v].push_back(u); len[v].push_back(l); } dfs(1,-1); ans=ans*2+n; long long d=gcd(ans,tot); cout<<ans/d<<'/'<<tot/d<<endl; }