5584:Stamp Rally 整体二分

We have an undirected graph with N vertices and M edges. The vertices are numbered 1 through N, and the edges are numbered 1 through M. Edge i connects vertices ai and bi. The graph is connected.

On this graph, Q pairs of brothers are participating in an activity called Stamp Rally. The Stamp Rally for the i-th pair will be as follows:

One brother starts from vertex xi, and the other starts from vertex yi.
The two explore the graph along the edges to visit zi vertices in total, including the starting vertices. Here, a vertex is counted only once, even if it is visited multiple times, or visited by both brothers.
The score is defined as the largest index of the edges traversed by either of them. Their objective is to minimize this value.
Find the minimum possible score for each pair.

Constraints
3≤N≤105
N−1≤M≤105
1≤ai<bi≤N
The given graph is connected.
1≤Q≤105
1≤xj<yj≤N
3≤zj≤N

输入
The input is given from Standard Input in the following format:

N M
a1 b1
a2 b2
:
aM bM
Q
x1 y1 z1
x2 y2 z2
:
xQ yQ zQ
输出
Print Q lines. The i-th line should contain the minimum possible score for the i-th pair of brothers.
样例输入
5 6
2 3
4 5
1 2
1 3
1 4
1 5
6
2 4 3
2 4 4
2 4 5
1 3 3
1 3 4
1 3 5
样例输出
1
2
3
1
5
5

题意

给出一个无向图,其中每条边的id按输入顺序给出(第一条边id为1,第二条边id为2,以此类推)。
现在有q次询问,每次询问包含一组x,y,z,表示当前有2个人分别从xy两点出发,总共经过的点数不小于z时,经过的边的最大id。(如果两个人访问同一个点则只算做经过一次)

思路

如果只有一次询问就很舒服,选取并查集配合size数组维护从每个点出发可以到达的点的个数,依次加边,check时首先判断xy是否联通,如果不连通则当前可达点的个数为sz[x]+sz[y],连通则为sz[x],判断是否大于等于z即可。显然,check时满足单调性。
但是如果对每次询问直接进行二分,时间复杂度最少也将达到 O ( n l o g n ∗ q ) O(nlogn*q) O(nlognq),何况如果mid减小并查集还要推倒重建,无法接受。
好在题目没有强制在线,可以先把所有询问读入进来,然后一并进行处理。

处理方法

建立如下结构体,其中lr表示当前二分的左右端点,v是答案在这个区间内的询问编号。(这里选择了对每个区间建立一个结构体元素,也可以选择对每一个询问建立一个元素)

struct data
{
   
    int l,r;
    vector<int>v;
};

将该元素放入队列中,每次取出队首,一分为二,然后把在当前区间内的询问编号放入左侧或右侧的元素中。如果一个区间内没有询问,那么这个区间也就没必要继续进队列了。当一个区间满足l=r,那么就可以把这个区间内的答案统计出来了。
因为使用了队列,相当于是对整体二分的树进行了层序遍历,由统计答案的性质,每一层并查集不需要推倒,mid>当前加入边id时,把中间没有加的边补上即可。只有当前mid比当前加入的边的id小的时候才会推倒(只会发生在由一层进入到下一层的时候),因此并查集只会被建立logn次,复杂度达到 O ( n l o g n ) O(nlogn) O(nlogn)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值