目录

CF280C-Game on Tree

CF280C-Game on Tree

题目:

题目描述:

Momiji has got a rooted tree, consisting of $ n $ nodes. The tree nodes are numbered by integers from $ 1 $ to $ n $ . The root has number $ 1 $ . Momiji decided to play a game on this tree.

The game consists of several steps. On each step, Momiji chooses one of the remaining tree nodes (let’s denote it by $ v $ ) and removes all the subtree nodes with the root in node $ v $ from the tree. Node $ v $ gets deleted as well. The game finishes when the tree has no nodes left. In other words, the game finishes after the step that chooses the node number $ 1 $ .

Each time Momiji chooses a new node uniformly among all the remaining nodes. Your task is to find the expectation of the number of steps in the described game.

输入格式:

The first line contains integer $ n $ $ (1<=n<=10^{5}) $ — the number of nodes in the tree. The next $ n-1 $ lines contain the tree edges. The $ i $ -th line contains integers $ a_{i} $ , $ b_{i} $ $ (1<=a_{i},b_{i}<=n; a_{i}≠b_{i}) $ — the numbers of the nodes that are connected by the $ i $ -th edge.

It is guaranteed that the given graph is a tree.

输出格式:

Print a single real number — the expectation of the number of steps in the described game.

The answer will be considered correct if the absolute or relative error doesn’t exceed $ 10^{-6} $ .

样例:

样例输入1:

1
2
2
1 2

样例输出1:

1
1.50000000000000000000

样例输入2:

1
2
3
3
1 2
1 3

样例输出2:

1
2.00000000000000000000

思路:

实现:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Problem: CF280C Game on Tree
// Contest: Luogu
// URL: https://www.luogu.com.cn/problem/CF280C
// Memory Limit: 250 MB
// Time Limit: 1000 ms
// Author: Ybw051114
//
// Powered by CP Editor (https://cpeditor.org)

#include "ybwhead/ios.h"
const int maxn = 1e5 + 10;
struct edge
{
    int v, nxt;
} e[maxn << 1];
int head[maxn], tot;
void __ADD(int u, int v)
{
    e[++tot] = {v, head[u]};
    head[u] = tot;
}
void add(int u, int v)
{
    __ADD(u, v);
    __ADD(v, u);
}
double ans;
int n;
void dfs(int u, int fa, int dep)
{
    ans += (double)1.0 / dep;
    for (int i = head[u]; i; i = e[i].nxt)
    {
        int v = e[i].v;
        if (v == fa)
            continue;
        dfs(v, u, dep + 1);
    }
}
int main()
{
    yin >> n;
    for (int i = 1; i < n; i++)
    {
        int u, v;
        yin >> u >> v;
        add(u, v);
    }
    dfs(1, 0, 1);
    yout << ans << endl;
    return 0;
}