hdu 2376 Average distance DFS 求树上任意两点距离和
2016-07-19 20:38
555 查看
hdu 2376 Average distance DFS 求树上任意两点距离和
题目链接:hdu 2376 Average distance题意:标题都已经说明了题意了。求树上任意两点距离和的平均值。
分析:分析过程和《 hdu
5723 Abandoned country 最小生成树+DFS》中求树上任意两点距离之和是完全一样的。思路就是先求出每条边两端的点的个数,然后对于每条边,假如该边两端的点的个数为A,B,那么这条边对总共的距离和的贡献值就是A*B*这条边的权值,然后将所有的边的贡献值累加就行了。
#include <cmath> #include <queue> #include <vector> #include <cstdio> #include <string> #include <cstring> #include <iomanip> #include <iostream> #include <algorithm> using namespace std; //#pragma comment(linker, "/STACK:1024000000,1024000000") #define FIN freopen("input.txt","r",stdin) #define FOUT freopen("output.txt","w",stdout) #define fst first #define snd second typedef __int64 LL; //typedef long long LL; typedef unsigned int uint; typedef pair<int, int> PII; const int INF = 0x3f3f3f3f; const double eps = 1e-6; const int MAXN = 10000 + 5; // const int MAXM = 1000000 + 5; struct TNode { int v, w; TNode() {} TNode(int v, int w) : v(v), w(w) {} }; int T, N; vector<TNode> G[MAXN]; int sum[MAXN]; LL ans; void init() { memset(sum, 0, sizeof(sum)); for (int i = 0; i < N; i++) G[i].clear(); } void dfs(int root, int father) { sum[root] = 1; for (int i = 0; i < G[root].size(); i++) { TNode& e = G[root][i]; int son = e.v; if (son == father) continue; dfs(son, root); sum[root] += sum[son]; ans += (LL)(sum[son] * (N - sum[son])) * e.w; } } int main() { #ifndef ONLINE_JUDGE FIN; #endif // ONLINE_JUDGE scanf("%d", &T); while (T --) { init(); scanf("%d", &N); int u, v, w; for (int i = 0; i < N - 1; i++) { scanf("%d %d %d", &u, &v, &w); G[u].push_back(TNode(v, w)); G[v].push_back(TNode(u, w)); } ans = 0; dfs(0, -1); int s = N * (N - 1) / 2; printf("%.6lf\n", (double) ans / s); } return 0; }
相关文章推荐
- tomcat从下载到使用
- 啊哈挑战 第67解答 又见神秘X
- [119] Pascal's Triangle II
- python调用hbase
- 实际应用中的C#加密
- mysql命令行
- Struts(八):动态方法调用
- hdoj--1862 EXCEL排序(sort+结构体)
- 【杭电-oj】-2803-The MAX(sort快排)
- dojo布局BorderContainer
- Activity的常用技巧
- windows版的php如何开启openssl
- 【GDOI模拟】彩色格子
- UVA-299 Train Swapping
- Scanner的例子
- 【BZOJ1014】【tyvj3486】火星人prefix,Splay+字符串hash
- POJ 2369 Permutations
- 用angular把页面中的元素按照页面分离开
- KNN算法(邻近算法)
- SpringMVC框架搭建流程