2376】Average distance (樹,平均距離,算貢獻)
題幹:
Given a tree, calculate the average distance between two vertices in the tree. For example, the average distance between two vertices in the following tree is (d 01 + d 02 + d 03 + d 04 + d 12 +d 13 +d 14 +d 23 +d 24 +d 34)/10 = (6+3+7+9+9+13+15+10+12+2)/10 = 8.6.
Input
On the first line an integer t (1 <= t <= 100): the number of test cases. Then for each test case:
One line with an integer n (2 <= n <= 10 000): the number of nodes in the tree. The nodes are numbered from 0 to n - 1.
n - 1 lines, each with three integers a (0 <= a < n), b (0 <= b < n) and d (1 <= d <= 1 000). There is an edge between the nodes with numbers a and b of length d. The resulting graph will be a tree.
Output
For each testcase:
One line with the average distance between two vertices. This value should have either an absolute or a relative error of at most 10 -6
Sample Input
1 5 0 1 6 0 2 3 0 3 7 3 4 2
Sample Output
8.6
題目大意:
給你一棵帶權值的樹(共有n*(n-1)/2條路徑),現在問你這些路徑的平均值是多少。
解題報告:
計算每條邊的入選的次數(也就是算這條邊對答案的貢獻),也就是它所連的兩個點的點的乘積。
AC程式碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long #define pb push_back #define pm make_pair #define fi first #define se second using namespace std; const int MAX = 2e5 + 5; struct Edge { int to; ll w; Edge(){} Edge(int to,ll w):to(to),w(w){} }; ll dp[MAX]; int n;//從0到n-1 vector <Edge> vv[MAX]; ll ans; void dfs(int cur,int root) { int up = vv[cur].size(); ll res = 0; for(int i = 0; i<up; i++) { Edge v = vv[cur][i]; if(v.to == root) continue; // if(v.to == root) { // res += v.w; // continue; // } // ll tmp = dfs(v.to,cur); // ans += tmp; // res += tmp; dfs(v.to,cur); dp[cur] += dp[v.to]; ans += dp[v.to] * (n-dp[v.to]) * v.w; } // return res; } int main() { int t; cin>>t; while(t--) { scanf("%d",&n); ans=0; for(int i = 0; i<n; i++) vv[i].clear(),dp[i] = 1; for(int i = 1; i<=n-1; i++) { int a,b; ll w; scanf("%d%d%lld",&a,&b,&w); vv[a].pb(Edge(b,w)); vv[b].pb(Edge(a,w)); } //ans += dfs(0,-1); dfs(0,-1); printf("%.6f\n",ans*1.0/(n*(n-1)/2)); } return 0 ; }
總結:
程式碼中註釋掉的是寫的一個longlong返回型別的一個dfs函式的思路,,,是不對的。。。那樣寫的話思路不是很明確,,應該得搞半天或許能搞出來、、、