1875. Small tree
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
Description
There is a rooted tree which has N nodes numbered form 0 to N-1.Root is labeled 0.Each edge connects two nodes with a weight. Your job is to find S, a set of nodes {s1, s2…. sm} (0<=m<N), satisfying that:
a) Root is not in S, which means,0<si<N,1<=i<=m;
b) There is only one common ancestor between si and sj, which means, they have no common ancestor except root.
c) There are two associate set W, {w1,w2….wm}, and D, {d1,d2….dm},wi is the sum of weights of the path from root to si, di is the edge numbers of the path from root to si. The average outcome of S = ∑wi / ∑di (1<=i<=m) is maximal.
Input
There is a number T in the first line which is the number of test cases.
Each case begins with a integer n (2<=n<=1000), the number of nodes of the tree
Next n-1 lines each contains three integers i, j, k, indicating there is a directed edge from i to j with weight k.
Output
Output a floating point number for each case, which is the maximum average weight of S. Exact to 0.01.
Sample Input
3 1 2 0 1 2 3 0 1 1 0 2 2
Sample Output
0.00 2.00 2.00
Hint
If your got a WA, maybe it's an accuracy error and you should plus your answer with an 1e-10
// Problem#: 1875
// Submission#: 3590237
// The source code is licensed under Creative Commons Attribution-NonCommercial-ShareAlike 3.0 Unported License
// URI: http://creativecommons.org/licenses/by-nc-sa/3.0/
// All Copyright reserved by Informatic Lab of Sun Yat-sen University
#include <stdio.h>
#include <string.h>
#include <vector>
using namespace std;
const int MAXN = 1001;
struct node {
int v, w;
};
vector<node> tree[MAXN];
double ans;
void dfs(int x, int dep, int sum) {
if (sum / double(dep) > ans) ans = sum / double(dep);
for (int i = 0; i < tree[x].size(); i++) {
int j = tree[x][i].v;
dfs(j, dep + 1, sum + tree[x][i].w);
}
}
int main() {
int i, j, tn, x, y, n;
node tmp;
scanf("%d", &tn);
while (tn--) {
scanf("%d", &n);
for (i = 0; i < n; i++) tree[i].clear();
for (i = 0; i < n - 1; i++) {
scanf("%d%d", &x, &y);
scanf("%d", &tmp.w);
tmp.v = y;
tree[x].push_back(tmp);
}
ans = 0;
int size = tree[0].size();
for (i = 0; i < size; i++) {
j = tree[0][i].v;
dfs(j, 1, tree[0][i].w);
}
printf("%.2lf\n", ans + 1e-10);
}
return 0;
}