Codeforces Contest 1087 problem D Minimum Diameter Tree——所有路径和一定,树上直径最小

You are given a tree (an undirected connected graph without cycles) and an integer s.

Vanya wants to put weights on all edges of the tree so that all weights are non-negative real numbers and their sum is s. At the same time, he wants to make the diameter of the tree as small as possible.

Let’s define the diameter of a weighed tree as the maximum sum of the weights of the edges lying on the path between two some vertices of the tree. In other words, the diameter of a weighed tree is the length of the longest simple path in the tree, where length of a path is equal to the sum of weights over all edges in the path.

Find the minimum possible diameter that Vanya can get.

Input
The first line contains two integer numbers n and s (2≤n≤105, 1≤s≤109) — the number of vertices in the tree and the sum of edge weights.

Each of the following n−1 lines contains two space-separated integer numbers ai and bi (1≤ai,bi≤n, ai≠bi) — the indexes of vertices connected by an edge. The edges are undirected.

It is guaranteed that the given edges form a tree.

Output
Print the minimum diameter of the tree that Vanya can get by placing some non-negative real weights on its edges with the sum equal to s.

Your answer will be considered correct if its absolute or relative error does not exceed 10−6.

Formally, let your answer be a, and the jury’s answer be b. Your answer is considered correct if |a−b|max(1,b)≤10−6.

Examples
inputCopy
4 3
1 2
1 3
1 4
outputCopy
2.000000000000000000
inputCopy
6 1
2 1
2 3
2 5
5 4
5 6
outputCopy
0.500000000000000000
inputCopy
5 5
1 2
2 3
3 4
3 5
outputCopy
3.333333333333333333

题意:

给你n个点,组成一棵树,让你自己给每条边加一个非负权值,但是所有的边的值加起来要等于s,最终使得最短路的最大值最小。

题解:

乍一看毫无思路,CF好像这种题很多,每个都是不同的解法。然后这道题我是从第三个例子中看出来,其实中间的这些点都是毫无意义的,有用的就是叶子结点,答案就是s*2/叶子节点的数量。

#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
vector<int>vec[N];
int main()
{
    int n;
    double s;
    scanf("%d%lf",&n,&s);
    int x,y;
    for(int i=1;i<=n-1;i++)
        scanf("%d%d",&x,&y),vec[x].push_back(y),vec[y].push_back(x);
    double sum=0;
    for(int i=1;i<=n;i++)
        if(vec[i].size()==1)
            sum+=1;
    printf("%.10f\n",s*2/sum);
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值