日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【HDU - 2376】Average distance (树,平均距离,算贡献)

發布時間:2023/12/10 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【HDU - 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函數的思路,,,是不對的。。。那樣寫的話思路不是很明確,,應該得搞半天或許能搞出來、、、

總結

以上是生活随笔為你收集整理的【HDU - 2376】Average distance (树,平均距离,算贡献)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。