Codeforces Round #582 (Div. 3) G. Path Queries

題目鏈接:http://codeforces.com/contest/1213/problem/G
題意:給你一個n個節點的樹 點與點之間的邊有權值 m此查詢
求有多少點對的簡單路徑上的邊的最大值小等於q
思路:對查詢進行排序,使用並查集進行加邊保證,目前所有集合裏面的邊都滿足要求,對於任何兩個不同的集合 其本身的點對必然滿足要求,合併集合後 內部點對發生改變點對數目增加 變爲(a+b*(a+b+1)/2 -a* (a+1) /2 + b*(b+1)/2
AC代碼:

#include <bits/stdc++.h>
using namespace std;
#define R register
#define ll long long
const int MaxN = 2e5 + 10;
struct edge
{
    int u, v, w;
    bool operator<(const edge x) const { return w < x.w; }
} e[MaxN << 1];
struct query
{
    int q, id;
    bool operator<(const query x) const { return q < x.q; }
} query[MaxN];
ll ans[MaxN], now;
int n, q, pos = 0, u, v, f[MaxN], size[MaxN];
ll getsize(ll x)
{
    return 1ll * (x - 1ll) * x / 2;
}
int getf(int x)
{
    if (f[x] != x)
        f[x] = getf(f[x]);
    return f[x];
}
int main()
{
    scanf("%d%d", &n, &q);
    for (int i = 1; i <= n; i++)
        f[i] = i, size[i] = 1;
    for (int i = 1; i < n; i++)
        scanf("%d%d%d", &e[i].u, &e[i].v, &e[i].w);
    sort(e + 1, e + n);
    for (int i = 1; i <= q; i++)
        scanf("%d", &query[i].q), query[i].id = i;
    sort(query + 1, query + 1 + q);
    for (int i = 1; i <= q; i++)
    {
        while (pos < n - 1 && e[pos + 1].w <= query[i].q)
        {
            ++pos;
            u = getf(e[pos].u), v = getf(e[pos].v);
            if (u == v)    continue;
            now = now - getsize(size[u]) - getsize(size[v]) + getsize(size[u] + size[v]);
            size[u] += size[v], f[v] = u;
        }
        ans[query[i].id] = now;
    }
    for (int i = 1; i <= q; i++)
        printf("%lld ", ans[i]);
    return 0;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章