牛客小白月赛23 G.树上求和

还是这样的图论题做的太少了,其实不难想。

1、DFS跑一遍求出每一个点的子树大小

2、贪心排序按每条边出现在树链中的次数分配权值,出现的次数多的权值小。

仔细说一下稍微有点难想的每条边出现的次数。

代码:

#include <iostream>
#include <malloc.h>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#define IO                       \
    ios::sync_with_stdio(false); \
    // cin.tie(0);                  \
    // cout.tie(0);
using namespace std;
typedef long long LL;
const int maxn = 1e5 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
struct Edge
{
    int before;
    int to;
} e[maxn << 1];
int head[maxn], size[maxn], n, k, cnt;
LL c[maxn];
void add(int u, int v)
{
    e[k].before = head[u];
    e[k].to = v;
    head[u] = k++;
}
void DFS(int u, int fa)
{
    size[u] = 1;
    for (int i = head[u]; i != -1; i = e[i].before)
    {
        int v = e[i].to;
        if (v != fa)
        {
            DFS(v, u);
            size[u] += size[v];
            c[++cnt] = 1LL * (n - size[v]) * size[v];
        }
    }
}
bool cmp(LL a, LL b)
{
    return a > b;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
    freopen("in.txt", "r", stdin);
    // freopen("out.txt", "w", stdout);
#endif
    IO;
    int x, y;
    memset(head, -1, sizeof head);
    cin >> n;
    for (int i = 0; i < n - 1; i++)
    {
        cin >> x >> y;
        add(x, y);
        add(y, x);
    }
    DFS(1, 0);
    sort(c + 1, c + cnt + 1, cmp);
    LL ans = 0;
    for (int i = cnt; i >= 1; i--)
    {
        ans += 1LL * i * c[i];
    }
    cout << ans;
    return 0;
}
发布了82 篇原创文章 · 获赞 29 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_44115065/article/details/105025105
今日推荐