hdu 5441 并查集 + 单调序列

Jack likes to travel around the world, but he doesn’t like to wait. Now, he is traveling in the Undirected Kingdom. There are n cities and m bidirectional roads connecting the cities. Jack hates waiting too long on the bus, but he can rest at every city. Jack can only stand staying on the bus for a limited time and will go berserk after that. Assuming you know the time it takes to go from one city to another and that the time Jack can stand staying on a bus is x minutes, how many pairs of city (a,b) are there that Jack can travel from city a to b without going berserk?

这个题目上手之前是队友在做,结果他们两个都tle掉了,蓝后我看的时候,突然觉得这和题目不就是询问嘛,每次询问并不改变已经有的数据,所以就对每次询问排序,然后根据每个询问的 X 处理,这样就相当于对最大的那个X进行处理了;  蓝后在用带权的并查集一做就好了。 复杂度就是O(n),如果还是不行就太丧心了,我当时如是的想到,并对队友说。蓝后在队友按照这个思路wrong了一发在找到不对再ac之后,窝居然还没打完,果然窝这个渣渣基础太弱。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
struct querry{
    int x,id;
    bool operator < (const querry &b) const{
        return x < b.x;
    }
};
struct Edge{
    int u,v,c;
    bool operator < (const Edge &b) const{
        return c <b.c;
    }
};
querry ask[5010];
Edge g[100010];
int p[20010];
int r[20010];
int ans[5010];
int n,m,q;
int findl (int x)
{
    if(x == p[x]) return x;
    else
        return p[x] = findl(p[x]);
}

void unionl(int x, int y){
    x = findl(x);
    y = findl(y);
    if(x > y) swap(x , y);
    p[y] = x;
    r[x] += r[y];
}
void init ()
{
    for(int i = 1; i <= n; i++)
        p[i] = i;
    for(int i = 1; i <= n; i++)
        r[i] = 1;
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d%d%d",&n,&m,&q);
        init();
        for(int i = 1; i <= m; i++)
        {
            scanf("%d%d%d",&g[i].u,&g[i].v,&g[i].c);
        }
        sort(g+1,g+1+m);
        for(int i = 1; i <= q; i++)
        {
            scanf("%d",&ask[i].x);
            ask[i].id = i;
        }
        sort(ask+1,ask+1+q);
        int j = 1,tmp = 0;
        for(int i = 1; i <= q; i++)
        {
            while(j <= m && g[j].c <= ask[i].x)
            {
                int u = findl(g[j].u);
                int v = findl(g[j].v);
                j++;
                if(u == v) continue;
                tmp +=(r[u]+r[v])*(r[u]+r[v]-1) - (r[u])*(r[u]-1) - (r[v])*(r[v]-1);
                unionl(u,v);
            }
            ans[ask[i].id] = tmp;
        }
        for(int i = 1; i <= q; i++)
            printf("%d\n",ans[i]);

    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值