The 2021 ICPC Asia Jinan Regional Contest

K Search For Mafuyu

思路:

图论+dfs,比赛的时候想成贪心了,导致用贪心做多写了好多没用的函数,虽然最后过了,但多花了好多好多时间,这个可以画几个图算一下,和遍历子树的顺序没关系,不管怎么遍历子树,最后总的和都是相同的,所以我们直接深搜每个子树就可以了,本来很简单的题因为想歪了多花了这么长时间。。。。唉。。。。

#include <bits/stdc++.h>

#define IOS ios::sync_with_stdio(false);cin.tie(0);

using namespace std;

typedef long long LL;
typedef pair<int, int> PII;

const int N = 1010, M = 1010, MOD = 998244353;
const double PI = acos(-1);

int n;
int e[2 * N], ne[2 * N], h[N], idx;
int dist, sum, res;
bool st[N];

void init()
{
    memset(h, -1, sizeof h);
    memset(st, 0, sizeof st);
    idx = 0;
    st[1] = 1;
    dist = 0;
    sum = 1;
    res = 0;
}

void add(int a, int b)
{
    e[idx] = b, ne[idx] = h[a], h[a] = idx++;
}

void dfs(int u)
{
    if(sum == n)
        return;

    for (int i = h[u]; i != -1; i = ne[i])
    {
        int j = e[i];
        if(st[j])
            continue;
        st[j] = 1;

        sum++;//当前遍历到的结点的个数
        dist++;
        res += dist;
        dfs(j);
        dist++;
    }
}

int main()
{
    IOS;
    int T;
    cin >> T;
    while(T -- )
    {
        cin >> n;
        init();
        for (int i = 1; i <= n - 1; i ++ )
        {
            int a, b;
            cin >> a >> b;
            add(a, b), add(b, a);
        }

        dfs(1);
        printf("%.10lf\n", (double)1.0 * res / (n - 1));
    }
    return 0;
}

 

上一篇:The 2021 Zhejiang University City College Freshman Programming Contest


下一篇:LeetCode笔记:Weekly Contest 276