题干:
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函数的思路,,,是不对的。。。那样写的话思路不是很明确,,应该得搞半天或许能搞出来、、、