Path Queries【Codeforces Round #582 (Div. 3).G】【dsu on tree】

codeforces 1213 G 题目链接


  昨晚上比赛的时候看到了这样的(u, v)对,就想到了这几天学的点分治,但是这里有个确实处理不了的问题,就是对已有点的贡献是不能反馈回去的,所以,到最后答案都是少的。

  然后今天的时候,看到了题目中给的算法标签,,我就想到了,不如对所有的边升序排序,然后去dsu on tree(树上瞎搞),然后似乎就是可以求得答案了。

  这里,先升序排序所有的边,然后我们去把所有的对应目前的边权去求答案,它所生成的答案(自己产生),跟现在所在的子树上的点有关,而答案数,是这棵子树上的点的个数的C(siz, 2),当然,我们需要容斥去减去多出来的部分,然后求答案即可。

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define efs 1e-6
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
using namespace std;
typedef double lb;
typedef unsigned long long ull;
typedef long long ll;
const int maxN = 2e5 + 7;
int N, Q, root[maxN], lsan[maxN], tot;
int fid(int x) { return x == root[x] ? x : root[x] = fid(root[x]); }
ll ans = 0, siz[maxN], Ques[maxN] = {0};
struct Eddge
{
    int u, v;
    ll w;
    Eddge(int a=0, int b=0, ll c=0):u(a), v(b), w(c) {}
    friend bool operator < (Eddge e1, Eddge e2) { return e1.w < e2.w; }
}edge[maxN];

inline void init()
{
    for(int i=1; i<=N; i++) root[i] = i;
    for(int i=1; i<=N; i++) siz[i] = 1;
}
int main()
{
    scanf("%d%d", &N, &Q);
    init();
    for(int i=1; i<N; i++) { scanf("%d%d%lld", &edge[i].u, &edge[i].v, &edge[i].w); lsan[i] = (int)edge[i].w; }
    sort(edge + 1, edge + N);
    sort(lsan + 1, lsan + N);
    tot = (int)(unique(lsan + 1, lsan + N) - lsan - 1);
    for(int i=1, u, v; i<N; i++)
    {
        u = fid(edge[i].u); v = fid(edge[i].v);
        ans -= siz[u] * (siz[u] - 1) / 2;
        ans -= siz[v] * (siz[v] - 1) / 2;
        root[u] = v;
        siz[v] += siz[u];
        ans += siz[v] * (siz[v] - 1) / 2;
        Ques[edge[i].w] = ans;
    }
    int qi;
    while(Q--)
    {
        scanf("%d", &qi);
        qi = (int)(upper_bound(lsan + 1, lsan + tot + 1, qi) - lsan - 1);
        printf("%lld ", Ques[lsan[qi]]);
    }
    printf("\n");
    return 0;
}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wuliwuliii

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值