假如 DS 参加 CSP-S 2025
toolong114514 · · 休闲·娱乐
前情提要
看到此文,突然想让 DS 做一下今年的 CSP-S,便写了这篇专栏。
打开深度思考,关闭联网搜索。
以洛谷作为唯一的评测方式。
提示词:
你是一位算法竞赛选手,请完成以下题目:[题面]
并未给出题面以外的样例。
本人贡献:处理生成文本的格式、评价做法和代码,提交测试。
本人认为贡献显然超过 AI。
T1
::::info[思考过程(388s/6.5min)] 题目要求将n个新成员分配到三个部门,且每个部门的人数不超过n/2。求最大的满意度之和。
观察:每个成员必须被分配到一个部门,且每个部门的人数不能超过n/2。由于n是偶数,所以每个部门最多n/2人。
我们可以考虑动态规划?但是n最大为10^5,而且有三个部门,直接状态可能太大。
另一种思路:如果没有人数限制,那么每个成员直接选择满意度最高的部门即可。但有人数限制,所以我们需要调整。
我们可以先考虑每个成员都选择第一个部门,然后调整一些成员到其他部门。但部门有三个,调整比较复杂。
实际上,这个问题可以转化为:每个成员有三种选择,我们需要给每个成员分配一个部门,使得每个部门的人数不超过n/2,并且总满意度最大。
由于部门只有三个,我们可以枚举三个部门的人数分配?但n可能很大,枚举量是O(n^3)不可行。
另一种思路:考虑网络流?但是n=10^5,边数可能很大,而且有三个部门,建图可能比较复杂。
我们注意到,问题实际上是一个带容量限制的分配问题。每个部门容量为n/2。我们可以这样建图: 源点 -> 三个部门(容量分别为n/2) 部门 -> 成员(容量为1,费用为满意度?但这里每个成员只能选一个部门) 成员 -> 汇点(容量为1)
但是这样建图,边数是从部门到每个成员,有3n条边,然后跑最大费用最大流?因为满意度是非负的,所以我们可以用最小费用流(取负)?但是n=10^5,节点数大约为n+3+2≈10^5,边数3n,费用流算法可能能够通过?但是最坏情况可能不行。
或者我们考虑贪心?或者动态规划?
观察:三个部门的人数限制都是n/2。那么总人数是n,所以每个部门的人数至少为0,最多为n/2。实际上,由于总人数n,三个部门的人数分配必须满足:每个部门<=n/2,且三个部门人数之和为n。
我们考虑每个成员的选择。对于每个成员i,如果我们知道了他不选哪个部门,那么他就在剩下的两个部门中选一个满意度较大的?但这样不一定全局最优。
另一种思路:我们可以先让所有成员都选择部门1,然后考虑将一些成员调整到部门2和部门3。但调整时可能会相互影响。
实际上,我们可以将问题转化为:每个成员最初选择部门1,然后我们可以选择一些成员改为部门2,一些改为部门3。但改的时候,部门2和部门3的总人数不能超过n/2?不对,每个部门都不能超过n/2。
设部门1、2、3的人数分别为x,y,z,则x+y+z=n,且x,y,z<=n/2。
那么x至少为n - n/2 - n/2 = 0?因为n是偶数,所以n/2*2=n,那么如果两个部门都达到n/2,第三个部门就是0。所以x,y,z的范围是0到n/2。
我们考虑每个成员i,如果他从部门1调整到部门2,获得的收益是(a[i][2]-a[i][1]);调整到部门3,收益是(a[i][3]-a[i][1])。那么总收益就是初始总满意度(全部选部门1)加上调整的收益。
但是调整时,我们有限制:调整到部门2的人数不能超过n/2,调整到部门3的人数不能超过n/2,而且同时调整到部门2和部门3的总人数不能超过n?实际上,因为部门1的人数x=n-y-z,而x必须<=n/2,所以y+z>=n/2?不对,因为x<=n/2 => n-y-z<=n/2 => y+z>=n/2。同时y<=n/2, z<=n/2。
所以调整后,y和z需要满足:y<=n/2, z<=n/2, 且y+z>=n/2且y+z<=n(因为总人数n)。
但注意,我们调整时,每个成员只能调整一次(要么调到2,要么调到3,要么不动)。所以我们需要选择一部分成员调整到2,一部分调整到3,使得总收益最大,且满足y<=n/2, z<=n/2, 且y+z<=n(实际上y+z<=n是自然的,因为总人数n,部门1至少0人)?实际上,部门1的人数x=n-y-z,而x>=0,所以y+z<=n;同时x<=n/2 => y+z>=n/2。
所以问题转化为:我们需要选择两个集合S2和S3(互不相交),分别表示调整到部门2和部门3的成员集合。那么总收益为:sum{i在S2}(a[i][2]-a[i][1]) + sum{i在S3}(a[i][3]-a[i][1])。并且|S2|<=n/2, |S3|<=n/2, 且|S2|+|S3|>=n/2且<=n(但<=n是自然的,因为最多n个成员)。
但是注意,我们并不要求|S2|+|S3|>=n/2?因为部门1的人数x=n-|S2|-|S3|,而x<=n/2,所以|S2|+|S3|>=n/2。所以条件为: 0<=|S2|<=n/2, 0<=|S3|<=n/2, 且n/2<=|S2|+|S3|<=n
然而,我们注意到|S2|+|S3|<=n是自动满足的,因为总成员数n。所以实际上限制是: |S2|<=n/2, |S3|<=n/2, 且|S2|+|S3|>=n/2.
那么问题就是:我们需要选择两个集合S2和S3(不相交),使得|S2|<=n/2, |S3|<=n/2, 且|S2|+|S3|>=n/2,并且总收益最大。
如何求解?我们可以枚举|S2|和|S3|?但n很大,枚举不行。
另一种思路:我们可以先考虑每个成员i,我们可以有两种调整选择:调整到2的收益b_i = a[i][2]-a[i][1],调整到3的收益c_i = a[i][3]-a[i][1]。那么对于每个成员,我们有两种收益值。我们需要决定每个成员是调整到2、调整到3还是不调整(不调整收益为0)。但注意,不调整实际上就是留在部门1,收益为0。
但是问题在于,我们选择S2和S3时,每个成员只能被选择一次(即不能同时调整到2和3)。所以对于每个成员,我们有三种选择:不调整(收益0)、调整到2(收益b_i)、调整到3(收益c_i)。我们需要最大化总收益,同时满足|S2|<=n/2, |S3|<=n/2, 且|S2|+|S3|>=n/2。
注意:这里我们并不要求每个成员必须调整?实际上,不调整也是允许的。
那么,我们如何选择?我们可以尝试先假设所有成员都可以调整,但需要满足人数限制。
我们可以这样:考虑每个成员i,我们定义如果让他调整到2,收益为b_i;调整到3,收益为c_i。那么如果我们强制要求调整的总人数为k(k>=n/2),那么我们需要从所有成员中选择k个调整,每个调整有两种选择(2或3),但两种选择的人数分别不能超过n/2。那么对于每个成员,如果我们选择他调整,那么我们会选择max(b_i, c_i)吗?不一定,因为如果选择b_i,那么占用一个部门2的名额;选择c_i,占用部门3的名额。而部门2和部门3的名额都是有限的(最多n/2)。
所以问题可以看作:我们需要选择k个人(k>=n/2且k<=n)进行调整,然后为每个调整的人分配部门2或部门3,使得部门2的人数不超过n/2,部门3的人数不超过n/2,并且总收益最大。
那么,我们可以枚举k吗?k从n/2到n?然后对于每个k,我们如何计算最大收益?
对于固定的k,我们想要从n个人中选出k个人,然后为每个选出来的人分配部门2或部门3,使得部门2的人数不超过n/2,部门3的人数不超过n/2,并且总收益最大。
我们可以这样:先考虑每个成员i,如果我们强制他调整到部门2,收益为b_i;调整到部门3,收益为c_i。那么对于每个成员,调整的最大收益是max(b_i, c_i)吗?但如果我们部门2的名额有限,部门3的名额有限,那么我们就需要权衡。
实际上,我们可以先假设每个成员都调整到收益最大的那个部门,但如果那个部门名额满了,就只能调整到另一个部门。但这样贪心可能不是最优,因为可能一个成员调整到部门2的收益很高,但部门2名额紧张,而另一个成员调整到部门2的收益较低但调整到部门3的收益也很高,那么可能让第一个成员调整到部门2,第二个成员调整到部门3更好。
另一种思路:我们可以将成员分为两类:一类是调整到部门2收益更高(即b_i>=c_i),另一类是调整到部门3收益更高(即c_i>b_i)。那么对于第一类,我们优先考虑部门2,如果部门2名额满了,再考虑部门3;对于第二类,优先考虑部门3,如果部门3名额满了,再考虑部门2。这样贪心是否可行?
但注意,我们可能有时需要牺牲一些高收益的调整,因为名额限制?实际上,我们可以用排序贪心。
具体步骤:
计算初始总满意度sum1 = sum(a[i][1])。
计算每个成员的b_i = a[i][2]-a[i][1], c_i = a[i][3]-a[i][1]。
我们将成员分为两组: 组A: b_i >= c_i // 即调整到部门2更划算,或者一样 组B: c_i > b_i // 调整到部门3更划算
对组A按b_i降序排序,对组B按c_i降序排序。
我们枚举调整的总人数k(从n/2到n),然后计算在k个人调整的情况下的最大收益。
但是枚举k可能复杂度为O(n),然后对于每个k如何快速计算?我们可以预处理。
我们考虑:设我们最终选择x个人调整到部门2,y个人调整到部门3,则x+y=k,且x<=n/2, y<=n/2。
那么总收益 = 组A中选择一部分人调整到部门2(收益b_i)和一部分人调整到部门3(收益c_i) + 组B中选择一部分人调整到部门2(收益b_i)和一部分人调整到部门3(收益c_i)。
由于组A中的人我们优先考虑部门2,组B中的人优先考虑部门3,所以我们可以这样:
假设我们最终部门2的人数为x,部门3的人数为y,那么我们从组A中选取前x个部门2的收益(如果组A人数不足x,则从组B中补一些部门2的收益?但组B的人部门2的收益较低),同样从组B中选取前y个部门3的收益(如果组B人数不足y,则从组A中补一些部门3的收益)。
但实际上,我们可能并不需要这样复杂。我们可以预先设定:部门2的名额最多为n/2,部门3的名额最多为n/2,然后我们从所有成员中选择调整到部门2和部门3的收益最大的方案?但每个成员只能调整到一个部门。
我们可以这样贪心:首先,对于每个成员i,我们记录其调整到部门2的收益b_i和调整到部门3的收益c_i。然后,我们考虑一个贪心策略:每次选择调整收益最大的那个成员和那个部门?但要注意,一个成员只能调整一次。
具体来说,我们可以用三个堆?或者用排序。
另一种思路:我们可以将问题看作,有2n个选项(每个成员有两个选项:调整到2或调整到3),但每个成员最多被选一次,而且部门2的总选项最多选n/2次,部门3的总选项最多选n/2次。那么这就是一个带容量限制的2n个物品中选择的问题,每个物品有一个收益,且每个成员的两个物品最多选一个,部门2的物品最多选n/2个,部门3的物品最多选n/2个。我们要选择若干物品,使得总收益最大。
这就是一个典型的带分组和容量限制的选择问题。我们可以用贪心+堆来解决。
方法如下:
将每个成员的两个选项视为两种物品,但这两个物品是互斥的(只能选一个)。
我们考虑先部门2和部门3的容量限制。
我们可以这样:首先,我们假设我们可以选部门2的n/2个收益最大的物品和部门3的n/2个收益最大的物品,但这样可能会一个成员被选两次。所以我们需要调整。
一个常见的做法:我们先将所有成员的两个选项放在一起排序?但这两个选项是互斥的,所以不能简单排序。
我们可以用费用流?但n=10^5,费用流可能不行。
另一种做法:我们考虑先强制每个成员只能调整一次,然后部门2和部门3分别有容量限制。我们可以用贪心:先忽略互斥条件,选出部门2的n/2个最大收益和部门3的n/2个最大收益,如果有一个成员被选了两个部门,那么我们就需要调整:要么让他选一个部门,要么都不选。
但这样可能比较复杂。
实际上,我们可以考虑动态规划:设dp[i][x][y]表示前i个成员,部门2选了x个,部门3选了y个时的最大收益。但x和y的范围是0..n/2,所以状态数是O(n(n/2)(n/2)) = O(n^3/4) = 10^5 5000 5000? 这显然不可行。
我们需要更高效的方法。
再看条件:部门2和部门3的容量分别为n/2,而且每个成员只能选一个部门。这实际上就是一个三分图匹配问题?但我们可以用贪心或排序。
我们考虑一个贪心策略:
首先,我们考虑每个成员,如果我们要调整,那么他带来的收益至少是max(b_i, c_i)?但如果我们必须选择两个部门的人数都不超过n/2,那么我们可以这样:
先假设我们只考虑调整到部门2和部门3的收益,然后我们选择收益最大的n次调整?但不行,因为一个成员只能调整一次。
我们可以将成员按照 max(b_i, c_i) - min(b_i, c_i) 来排序?或者按照 max(b_i, c_i) 排序。
一种已知的有效做法是:我们考虑部门2和部门3的容量限制,然后每个成员有三种选择:0(不调整)、1(调整到2)、2(调整到3)。我们可以用贪心:先让所有成员都不调整,然后我们考虑进行k次调整,每次调整选择当前能带来收益最大且不违反容量限制的调整。
具体步骤:
初始化:部门2容量为n/2,部门3容量为n/2。
我们用一个大根堆,存储每个成员调整到部门2的收益和调整到部门3的收益,但因为我们只能选一个,所以对于每个成员,我们记录其最大的调整收益以及对应的部门。
但是,当我们选择一个成员调整到部门2时,我们就不能再调整他到部门3了,而且部门2的容量减1。
我们可以用三个堆:
text 堆1:存储所有成员调整到部门2的收益(b_i)。 堆2:存储所有成员调整到部门3的收益(c_i)。 堆3:存储所有成员调整到部门2和部门3的收益差(即对于每个成员,如果我们已经选了他调整到部门2,那么如果我们想让他改为部门3,收益变化是c_i - b_i;反之亦然)?但这样可能复杂。 另一种方法:我们使用一个堆,堆中的元素是每个成员的两个调整选项,但当我们从堆中取出一个选项时,如果这个选项对应的部门还有容量,并且这个成员还没有被调整,那么我们就选择这个调整,然后把这个成员标记为已调整,并减少对应部门的容量。但如果这个选项对应的部门没有容量了,那么我们就跳过这个选项?这样不行,因为可能这个成员另一个部门选项还有容量且收益也很大。
我们可以这样:我们维护两个堆:堆A用于部门2,堆B用于部门3。每个堆存储的是对应部门的调整收益,以及成员编号。然后我们每次从两个堆的堆顶中选择收益最大的那个,如果这个部门还有容量,且这个成员还没有被选择,那么我们就选择这个调整,并标记这个成员已被选择。但如果这个成员已经被选择,那么我们就弹出继续。
但是,如果一个成员在两个堆中都有,那么当我们选择他在一个部门时,他在另一个部门的收益就应该无效。所以我们需要在选择了一个成员后,从另一个堆中删除他。
具体算法:
初始化: cap2 = n/2, cap3 = n/2 total_gain = 0 设置两个大根堆:heap2和heap3,分别存储(b_i, i)和(c_i, i) 设置一个数组used,表示成员i是否被选择,初始为false。
循环直到cap2和cap3都为0或者两个堆都为空: while heap2不为空且堆顶的成员已经被使用,弹出堆顶。 while heap3不为空且堆顶的成员已经被使用,弹出堆顶。 如果heap2为空且heap3为空,break。 如果heap2不为空且heap2的堆顶收益大于heap3的堆顶收益(或者heap3为空)且cap2>0: 选择heap2的堆顶,设其为(b_i, i),那么: total_gain += b_i cap2-- used[i] = true 然后从heap3中删除成员i?但实际上我们无法直接删除,所以我们可以在后面通过used来跳过。 否则,如果heap3不为空且cap3>0: 选择heap3的堆顶,设其为(c_i, i),那么: total_gain += c_i cap3-- used[i] = true
那么总满意度 = sum1 + total_gain
但是这样贪心是否正确?考虑这样一种情况:某个成员i在部门2的收益很高,在部门3的收益也很高,但是部门2的容量已经满了,而部门3还有容量,那么我们可能不会选他,因为我们在部门2的堆中取不到他(因为部门2满了),而在部门3的堆中取他时,他的收益可能不是最高的?但实际上,我们的贪心在部门2容量满后,就会一直从部门3中取,那么 eventually 会取到他吗?不会,因为我们的贪心每次取的是两个堆中收益最大的,但如果部门2的堆顶收益虽然大但部门2满了,我们就会取部门3的堆顶。所以如果部门2满了,我们就把部门2的堆清空?不对,我们应该继续考虑部门3的堆。
所以改进:当某个部门容量为0时,我们就不考虑这个部门的堆了。
算法修改:
我们循环直到两个堆都为空或者两个部门的容量都为0。
在循环中: 如果cap2>0且heap2的堆顶收益大于等于heap3的堆顶收益,那么我们就选heap2的堆顶(前提是这个成员未被使用)。 否则如果cap3>0,我们就选heap3的堆顶。 但如果cap2>0但heap2的堆顶成员已经被使用,那么我们弹出并继续。 同样,如果cap3>0但heap3的堆顶成员已经被使用,那么我们弹出并继续。
这样是否正确?我们举一个例子:
假设有两个成员: 成员1: b1=10, c1=8 成员2: b2=9, c2=7 部门容量都是1。
按照我们的贪心: 初始化:heap2: [10, 9];--堆顶是10;heap3: [8,7]--堆顶是8。 第一次:比较10和8,选择部门2的10,成员1被选,cap2变为0。 然后,我们检查heap2,堆顶是9,但cap2=0,所以不能选部门2。然后我们选部门3的堆顶8,但成员1已经被选,所以弹出8;然后部门3的堆顶变为7,成员2未被选,所以选部门3的7?总收益10+7=17。 但是,如果我们选成员2到部门2(收益9)和成员1到部门3(收益8),总收益9+8=17,是一样的。
所以这个贪心是正确的吗?在这个例子中结果相同。
再试一个例子: 成员1: b1=10, c1=5 成员2: b2=6, c2=8 部门容量都是1。 第一次:heap2堆顶10>heap3堆顶8,选成员1到部门2,cap2=0。 然后,heap2堆顶是6,但cap2=0,所以考虑heap3堆顶8,成员2未被选,选成员2到部门3,总收益10+8=18。 实际上最优就是18。
另一个例子: 成员1: b1=10, c1=1 成员2: b2=1, c2=8 部门容量都是1。 第一次:选部门2的10,成员1。 然后选部门3的8,成员2。总收益18。
但是考虑这种情况:部门2的容量有限,而部门3的容量充足,但有一个成员在部门2的收益非常高,在部门3的收益也很高,但另一个成员在部门2的收益较高,在部门3的收益较低。我们的贪心会先选部门2收益最高的,然后选部门3收益最高的,即使部门3收益最高的那个成员在部门2的收益也很高,但已经被选过了?这没有问题。
所以这个贪心策略似乎可行。
但是,有没有可能一个成员在部门2的收益很高,但部门2容量已满,那么我们就不能选他到部门2,而如果他到部门3的收益也很高,那么我们在部门3的堆中会选到他吗?不会,因为我们的贪心在部门2容量满后,就会只从部门3的堆中选,而部门3的堆中包括所有成员(包括那些在部门2收益高的成员)的部门3收益。所以我们会选到他的部门3收益,只要他的部门3收益足够高。
因此,我们可以用这个贪心算法。
步骤总结:
计算初始总满意度sum1 = sum(a[i][1])。
初始化两个大根堆:heap2和heap3,分别存储(b_i, i)和(c_i, i),其中b_i=a[i][2]-a[i][1], c_i=a[i][3]-a[i][1]。
初始化cap2 = n/2, cap3 = n/2。
初始化一个数组used,大小为n+1,初始为false。
total_gain = 0。
循环直到(cap2==0 && cap3==0) 或者 (heap2为空且heap3为空):
while heap2不为空且used[heap2.top().second]为true,则弹出heap2的堆顶。
while heap3不为空且used[heap3.top().second]为true,则弹出heap3的堆顶。
如果heap2为空且heap3为空,break。
如果cap2>0且heap2不为空,且(heap3为空或heap2.top().first >= heap3.top().first):
令item = heap2.top(),弹出heap2。
i = item.second
如果used[i]为true,则跳过(但我们已经检查过了,所以应该不会出现)。
否则:
total_gain += item.first
used[i] = true
cap2--
否则如果cap3>0且heap3不为空:
令item = heap3.top(),弹出heap3。
i = item.second
如果used[i]为true,则跳过。
否则:
total_gain += item.first
used[i] = true
cap3--
否则:
break
答案 = sum1 + total_gain
但是注意:收益b_i和c_i可能是负数?如果收益是负数,那么我们就不应该调整,因为调整反而降低总满意度。所以我们在贪心时,如果收益是负数,我们就不会选择,因为我们的堆是大根堆,负数会在堆底,我们在取的时候如果堆顶是负数,那么我们就不会选择?因为如果堆顶是负数,那么说明所有调整收益都是负数,那么我们就不要调整了。
但是,我们的算法在取堆顶时,如果堆顶是负数,那么我们会跳过吗?实际上,如果堆顶是负数,那么整个堆都是负数了,那么我们就不会选择调整。所以这样是合理的。
但是,我们是否可能选择负收益的调整?不可能,因为我们的贪心每次取最大收益,如果最大收益是负数,那么我们就不会继续了,因为cap2和cap3可能还有,但我们不会选择负收益。
因此,这个算法应该正确。
我们测试一下样例:
样例1:第一组数据
n=4
成员1: [4,2,1] -> b1=2-4=-2, c1=1-4=-3
成员2: [3,2,4] -> b2=2-3=-1, c2=4-3=1
成员3: [5,3,4] -> b3=3-5=-2, c3=4-5=-1
成员4: [3,5,1] -> b4=5-3=2, c4=1-3=-2
text
初始sum1=4+3+5+3=15。
构建堆:
heap2: [-2, -1, -2, 2] -> 堆顶是2,然后-1,-2,-2
heap3: [-3, 1, -1, -2] -> 堆顶是1,然后-1,-2,-3
现在,cap2=2, cap3=2。
第一次:比较heap2堆顶2和heap3堆顶1,选择2(成员4调整到部门2),收益2,cap2=1,标记成员4已使用。
第二次:heap2堆顶变为-1(但成员2的b2=-1),heap3堆顶是1(成员2的c2=1)。比较:-1<1,所以选择部门3的1(成员2调整到部门3),收益1,cap3=1,标记成员2已使用。
第三次:现在cap2=1, cap3=1。检查堆:heap2堆顶是-1(成员2已被使用,所以弹出?我们在每次循环前会检查。所以现在heap2中还有哪些?成员1、3的b_i都是-2,但成员1和3未被使用。所以heap2堆顶是-2(假设我们按值排序,相同值任意顺序)。heap3堆顶是-1(成员3的c3=-1)?但成员3未被使用。
比较:heap2堆顶-2和heap3堆顶-1,因为-2<-1,所以选择部门3的-1?但收益是负的,我们还要选吗?实际上,如果收益为负,我们就不应该调整了。但是我们的算法会继续吗?因为cap2和cap3都还有,所以我们会继续选择?但收益为负,我们不应该选择。
所以我们需要在收益为负时停止?我们可以修改:在从堆中取堆顶时,如果堆顶的收益小于0,那么我们就直接break?因为堆顶收益都小于0了,后面的收益更小,所以没有必要再调整了。
因此,在循环中,我们检查:
如果cap2>0且heap2不为空且heap2.top().first<0,那么我们就不要考虑heap2了?实际上,如果heap2堆顶收益小于0,那么整个heap2都小于0,同理heap3。
所以我们可以添加:
if (cap2>0 && !heap2.empty() && heap2.top().first <0) 则忽略heap2?但这样可能不对,因为可能heap3还有正收益?所以我们不能直接忽略。
我们应该这样:在每次选择前,如果堆顶收益小于0,那么我们就不要选择?因为选择负收益会降低总满意度。所以我们在比较时,如果heap2堆顶收益小于0,那么我们就认为heap2没有可选的;同样heap3堆顶收益小于0,则认为heap3没有可选的。
修改:
如果cap2>0且heap2不为空且heap2.top().first>=0,且(heap3为空或heap3.top().first<0或heap2.top().first>=heap3.top().first)),那么选heap2。
否则如果cap3>0且heap3不为空且heap3.top().first>=0,那么选heap3。
否则,break。
这样,当两个堆的堆顶收益都小于0时,我们就停止。
在上面的例子中,第三次时,heap2堆顶-2<0,heap3堆顶-1<0,所以停止。总收益=2+1=3,总满意度=15+3=18,正确。
样例2:第二组数据
4个成员:
成员1: [0,1,0] -> b1=1-0=1, c1=0-0=0
成员2: [0,1,0] -> b2=1, c2=0
成员3: [0,2,0] -> b3=2, c3=0
成员4: [0,2,0] -> b4=2, c4=0
初始sum1=0。
堆2: [1,1,2,2] -> 堆顶2
堆3: [0,0,0,0] -> 堆顶0
cap2=2, cap3=2。
第一次:选堆2的2(成员3),收益2,cap2=1。
第二次:选堆2的2(成员4),收益2,cap2=0。
然后,cap2=0,但堆2还有,但cap2=0了,所以接下来选堆3?但堆3的收益都是0,而且>=0,所以我们会选两个0?但这样总收益=2+2+0+0=4?但实际上,我们不需要调整到部门3,因为部门3的收益为0。但题目中部门3的收益为0,调整到部门3不会增加满意度,但也不会减少?所以调整到部门3也是允许的,但收益为0。那么总收益为4,正确。
但是,如果我们不调整到部门3,那么部门1的人数就是4,但部门1的人数不能超过2?因为每个部门不能超过n/2=2。所以我们必须调整至少2个人到其他部门。这里我们调整了2个人到部门2,已经满足了条件(部门1有2人,部门2有2人,部门3有0人),所以不需要再调整到部门3。所以实际上我们不需要选择部门3的调整。那么我们的算法在cap2=0后,还会选择部门3吗?因为部门3的收益为0,而且>=0,所以我们会选择?但这样我们会多调整两个人到部门3,但这样总收益不变(因为收益为0),所以也可以。但如果我们不想多调整,那么其实也没有关系,因为收益为0不影响总满意度。
所以算法正确。
样例3:第三组数据
2个成员:
成员1: [10,9,8] -> b1=9-10=-1, c1=8-10=-2
成员2: [4,0,0] -> b2=0-4=-4, c2=0-4=-4
初始sum1=10+4=14。
堆2: [-1,-4] -> 堆顶-1
堆3: [-2,-4] -> 堆顶-2
因为堆顶都是负数,所以不会调整,总满意度14?但预期是13。
为什么预期是13?因为题目中给出的方案是:第一个成员调整到部门2(收益9?但这里调整到部门2的收益是-1,因为从部门1调整到部门2,满意度从10变成9,收益是-1?)但为什么题目说第一个成员调整到部门2收益是9?不对,我们初始是部门1,满意度10,调整到部门2后满意度9,所以收益是9-10=-1。那么为什么总满意度是13?因为题目方案是:第一个成员到部门2(满意度9),第二个成员到部门1(满意度4),总满意度13。但我们的初始总满意度是14(两个都在部门1),调整第一个成员到部门2后,总满意度变成14-1=13。所以我们的算法中,调整收益是负的,所以不会调整,因此得到14?但实际正确答案是13?不对,因为题目要求每个部门不超过n/2=1。如果两个成员都在部门1,那么部门1有2人,超过1人,所以不满足条件。因此,我们必须至少调整一个人到其他部门。
所以我们的算法有问题:我们可能必须调整 even if the gain is negative? 因为有人数限制,所以即使调整收益为负,我们也必须调整以满足人数限制。
因此,我们不能在收益为负时停止。我们必须保证调整后每个部门的人数不超过n/2。也就是说,我们可能不得不进行一些负收益的调整。
那么,我们的贪心算法需要调整:我们需要保证最终调整的总人数至少为n/2?因为部门1的人数不能超过n/2,所以调整的总人数(即离开部门1的人数)至少为n/2?因为部门1最初有n个人,调整后部门1的人数为n - (调整到部门2的人数) - (调整到部门3的人数) = n - k,而n-k<=n/2 => k>=n/2。
所以我们必须调整至少n/2个人。因此,我们的算法必须选择至少n/2个调整,即使这些调整的收益是负的。
因此,我们不能因为收益为负就停止。我们需要至少选择n/2个调整。
修改算法:我们仍然使用两个堆,但我们现在必须选择至少n/2个调整。那么,我们如何保证至少选择n/2个调整?
我们可以:先不管收益是否为负,我们必须选择k>=n/2个调整。那么,我们首先按照收益从高到低选择,直到选满n/2个?即使收益为负也要选?但这样可能不是最优,因为负收益越小越好(即负收益的绝对值越大越不好)。
实际上,我们仍然可以用堆,但我们现在必须选满n/2个调整?不一定,因为我们可以调整多于n/2个,但至少n/2个。
但是,我们的算法目前是能选就选,直到两个部门容量为0。那么如果收益为负,我们还会选吗?目前我们的算法没有检查收益是否为负,所以会选。但在上面的样例3中,我们的算法会选吗?
样例3:n=2,cap2=1, cap3=1。
成员1: b1=-1, c1=-2
成员2: b2=-4, c2=-4
我们的算法:
第一次:比较heap2堆顶-1和heap3堆顶-2,因为-1>-2,所以选部门2的-1(成员1),cap2=0。
第二次:现在cap2=0,所以选部门3的堆顶-2(成员1?但成员1已经被选,所以弹出?然后堆顶是成员2的-4?那么选部门3的-4(成员2),cap3=0。
总收益 = (-1) + (-4) = -5,总满意度=14-5=9,但预期是13。
为什么是9?但预期是13,说明我们的算法选错了。
预期方案是:第一个成员到部门2(收益-1),第二个成员留在部门1(收益0),但这样部门1有1人,部门2有1人,满足条件,总满意度10+4-1=13?不对,第一个成员调整到部门2收益-1,所以总满意度14-1=13。但我们的算法却把第二个成员也调整了,收益为-4,所以总满意度14-1-4=9。
所以我们的算法可能在这种情况下会多选。
因此,我们必须控制调整的人数:我们至少需要n/2个调整,但可能不需要超过n/2个。在样例3中,我们只需要1个调整(因为n/2=1)即可满足条件。
所以问题在于,我们的算法可能会超过n/2个调整?因为部门2和部门3的容量总和是n,而我们需要的是调整总数至少n/2,但我们的算法会直到两个部门容量用尽才停止,这可能会导致调整人数超过n/2,而且可能包含负收益。
因此,我们需要修改:我们只需要调整至少n/2个人,但不超过n个人。那么,我们如何确定应该调整多少人?事实上,我们可以调整任意多于n/2的人,但超过n/2的人可能会带来负收益,所以我们应该只调整n/2个人如果超过n/2会带来负收益。
但是,有时调整超过n/2可能会带来正收益?但通常不会,因为正收益的调整我们会优先选择。
因此,我们可能需要先选择收益最高的n/2个调整?但收益最高的n/2个调整可能涉及部门2和部门3的容量限制。
一种思路:我们要求调整的总人数至少为n/2,那么我们可以用贪心选择收益最高的n/2个调整?但这n/2个调整必须满足部门2和部门3的人数不超过n/2。
那么,我们如何选择这n/2个调整?我们可以将每个成员的两个调整选项视为两个物品,但只能选一个,然后我们选择n/2个物品,使得部门2的物品不超过n/2,部门3的物品不超过n/2,并且总收益最大。
这相当于:从2n个物品中选择n/2个物品(每个成员最多选一个),使得部门2的物品不超过n/2,部门3的物品不超过n/2,最大化总收益。
注意:这里n/2是调整的人数,但实际上部门2和部门3的容量也是n/2,所以部门2的物品最多选n/2个,部门3的物品最多选n/2个,而且总共选n/2个物品。那么,我们实际上就是在2n个物品中选择n/2个物品,且部门2的物品最多选n/2个,部门3的物品最多选n/2个,这自然满足,因为n/2<=n/2。所以问题转化为:从2n个物品中选择n/2个物品(每个成员最多选一个),使得总收益最大。
那么,这就是一个简单的贪心:我们只要从所有2n个物品中选择收益最大的n/2个物品,但要求每个成员最多选一个。如果我们选择了一个成员的两个物品,那么我们就违反了每个成员最多选一个的条件。
所以我们可以:先将2n个物品按照收益降序排序,然后从大到小选择n/2个物品,但如果遇到同一个成员被选了两次,那么我们就不能选第二次。
但这样贪心是否正确?不一定,因为可能同一个成员的两个物品收益都很高,但我们只能选一个。
我们可以用贪心+并查集?或者用动态规划?但n=10^5,n/2=50000,2n=200000,所以排序后贪心选择是O(2n)的。
具体步骤:
1. 创建一个列表,包含所有2n个物品,每个物品用(收益, 成员id, 部门)表示。
2. 将这个列表按收益降序排序。
3. 初始化一个数组chosen,表示每个成员是否已经被选了一个物品,初始为false。
4. 初始化计数count=0,总收益gain=0。
5. 遍历排序后的列表,对于每个物品:
如果count < n/2 && 这个物品对应的成员还没有被选 && 这个物品的收益>=0(?但即使收益<0,我们也可能必须选,因为可能选不满n/2)?不对,我们可能必须选满n/2,即使有负收益。
但是,如果我们必须选满n/2,那么我们就得选,即使收益为负。所以我们在排序后,从高到低选,如果选不满n/2,那么我们就不得不选负收益的物品。
所以算法:
1. 创建列表L。
2. 排序。
3. 遍历L,如果当前成员未被选,且count < n/2,那么我们就选这个物品,count++,gain+=收益,标记成员为已选。
4. 如果遍历结束后 count < n/2,那么说明我们无法选满n/2个正收益的物品,那么我们就不得不选一些负收益的物品。但我们在排序时已经包括了负收益的物品,所以我们在遍历时不会跳过负收益,但因为排序后负收益在最后,所以我们会先选正收益,然后选负收益?但为什么还会选不满?因为可能成员数量不足?不会,成员有n个,每个成员有两个物品,所以至少有n/2个物品可选?因为n/2<=n,所以一定能选满n/2个物品。
因此,我们总是能选满n/2个物品。
但是,这样选是否满足部门2和部门3的人数限制?注意,我们这里没有考虑部门2和部门3的人数限制,因为部门2和部门3的人数限制是n/2,而我们只选了n/2个物品,所以部门2的物品最多n/2个,部门3的物品最多n/2个,自动满足。
所以这个算法正确。
样例3:用这个新算法。
2个成员,n/2=1。
物品列表:
成员1: department2: -1
成员1: department3: -2
成员2: department2: -4
成员2: department3: -4
排序后:[-1, -2, -4, -4]
我们从大到小选:第一个物品-1,成员1未被选,所以选中,count=1, gain=-1。
然后我们就选满了1个,停止。
总收益-1,总满意度14-1=13,正确。
样例1:第一组数据
n=4, n/2=2。
物品列表(收益,成员id):
成员4: department2: 2
成员2: department3: 1
成员2: department2: -1
成员1: department2: -2
成员3: department3: -1
成员1: department3: -3
成员3: department2: -2
成员4: department3: -2
排序后:[2,1,-1,-1,-2,-2,-2,-3]
选2个:
选2(成员4),标记成员4已选。
选1(成员2),标记成员2已选。
总收益2+1=3,总满意度15+3=18,正确。
样例2:第二组数据
n=4, n/2=2。
物品列表:
成员3: department2: 2
成员4: department2: 2
成员1: department2: 1
成员2: department2: 1
成员1: department3: 0
成员2: department3: 0
成员3: department3: 0
成员4: department3: 0
排序后:[2,2,1,1,0,0,0,0]
选2个:2(成员3)和2(成员4),总收益4,总满意度0+4=4,正确。
因此,我们可以用这种办法。
算法总结:
1. 计算初始总满意度sum1 = sum(a[i][1])。
2. 创建一个空列表L。
3. 对于每个成员i(1<=i<=n):
将 (a[i][2]-a[i][1], i, 2) 加入L。
将 (a[i][3]-a[i][1], i, 3) 加入L。
4. 将L按照收益值从大到小排序。
5. 初始化一个数组used,大小为n+1,初始为false。
6. count = 0, total_gain = 0。
7. 对于L中的每个物品(gain_val, i, dep):
如果 count < n/2 且 used[i] 为 false:
total_gain += gain_val
used[i] = true
count++
8. 答案 = sum1 + total_gain
注意:收益值可能是负数,但我们仍然要选,因为我们必须选满n/2个。
这个算法的时间复杂度是O(n log n),能够接受。
我们验证一下样例3的另一个情况:如果收益有正有负,我们总是选收益最高的n/2个,且每个成员只选一次。
因此,代码实现如下。
注意:题目有多组测试数据。
代码:
#include <bits/stdc++.h>
using namespace std;
int main() {
int t;
cin >> t;
while (t--) {
int n;
cin >> n;
vector<vector<int>> a(n, vector<int>(3));
long long sum1 = 0;
for (int i = 0; i < n; i++) {
for (int j = 0; j < 3; j++) {
cin >> a[i][j];
}
sum1 += a[i][0];
}
vector<tuple<int, int, int>> items; // (gain, id, dep)
for (int i = 0; i < n; i++) {
int gain2 = a[i][1] - a[i][0];
int gain3 = a[i][2] - a[i][0];
items.push_back({gain2, i, 2});
items.push_back({gain3, i, 3});
}
sort(items.begin(), items.end(), [](const auto &x, const auto &y) {
return get<0>(x) > get<0>(y);
});
vector<bool> used(n, false);
int count = 0;
long long total_gain = 0;
for (auto &[gain, id, dep] : items) {
if (count < n/2 && !used[id]) {
total_gain += gain;
used[id] = true;
count++;
}
}
cout << sum1 + total_gain << endl;
}
return 0;
}
我们提交一下,看看是否通过。
注意:收益可能为负数,但我们的算法会选满n/2个,即使有负数。
希望正确。
:::: ::::info[最终思路] 为了解决这个问题,我们需要将n个新成员分配到三个部门中,使得每个部门的人数不超过n/2,并且总满意度最大。由于n是偶数,每个部门最多容纳n/2个成员。我们需要在满足人数限制的前提下,最大化所有成员对其分配部门的满意度之和。
-
初始满意度计算:首先计算所有成员都被分配到第一个部门时的总满意度,作为初始值。
-
生成调整选项:对于每个成员,计算将其调整到第二个或第三个部门时的满意度增益(即新部门的满意度减去第一个部门的满意度)。
-
排序调整选项:将所有调整选项(包括调整到第二和第三部门)按增益从高到低排序。
-
选择最佳调整:从排序后的列表中选择前n/2个增益最高的调整选项,确保每个成员最多被调整一次。这样保证总调整人数至少为n/2,满足部门人数限制。
-
计算最终满意度:将初始满意度与总调整增益相加,得到最终的最大满意度。 ::::info[code] ```cpp #include <bits/stdc++.h> using namespace std;
int main() { ios_base::sync_with_stdio(false); cin.tie(0); int t; cin >> t; while (t--) { int n; cin >> n; vector<vector<int>> a(n, vector<int>(3)); long long sum1 = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < 3; j++) { cin >> a[i][j]; } sum1 += a[i][0]; }
vector<tuple<int, int, int>> items;
for (int i = 0; i < n; i++) {
int gain2 = a[i][1] - a[i][0];
int gain3 = a[i][2] - a[i][0];
items.push_back({gain2, i, 2});
items.push_back({gain3, i, 3});
}
sort(items.begin(), items.end(), [](const auto &x, const auto &y) {
return get<0>(x) > get<0>(y);
});
vector<bool> used(n, false);
int count = 0;
long long total_gain = 0;
for (const auto &item : items) {
if (count >= n / 2) break;
int gain = get<0>(item);
int id = get<1>(item);
int dep = get<2>(item);
if (!used[id]) {
total_gain += gain;
used[id] = true;
count++;
}
}
cout << sum1 + total_gain << '\n';
}
return 0;
}
::::
[record 20pts](https://www.luogu.com.cn/record/245846263)
## T2
::::info[code]
```cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
struct Edge {
int u, v;
ll w;
Edge(int u, int v, ll w) : u(u), v(v), w(w) {}
bool operator<(const Edge& other) const {
return w < other.w;
}
};
struct DSU {
vector<int> parent;
vector<int> rank;
DSU(int n) {
parent.resize(n+1);
rank.assign(n+1, 0);
for (int i = 1; i <= n; i++) parent[i] = i;
}
int find(int x) {
while (parent[x] != x) {
parent[x] = parent[parent[x]];
x = parent[x];
}
return x;
}
bool unite(int a, int b) {
a = find(a);
b = find(b);
if (a == b) return false;
if (rank[a] < rank[b]) swap(a, b);
parent[b] = a;
if (rank[a] == rank[b]) rank[a]++;
return true;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
int n, m, k;
cin >> n >> m >> k;
vector<Edge> original_edges;
for (int i = 0; i < m; i++) {
int u, v;
ll w;
cin >> u >> v >> w;
original_edges.push_back(Edge(u, v, w));
}
sort(original_edges.begin(), original_edges.end());
DSU dsu0(n);
vector<Edge> MST0_edges;
ll C0 = 0;
for (const Edge& e : original_edges) {
if (dsu0.unite(e.u, e.v)) {
MST0_edges.push_back(e);
C0 += e.w;
}
}
vector<ll> c(k);
vector<vector<ll>> a(k, vector<ll>(n));
for (int j = 0; j < k; j++) {
cin >> c[j];
for (int i = 0; i < n; i++) {
cin >> a[j][i];
}
}
vector<vector<Edge>> town_edges(k);
for (int j = 0; j < k; j++) {
for (int i = 0; i < n; i++) {
town_edges[j].push_back(Edge(n + j + 1, i + 1, a[j][i]));
}
sort(town_edges[j].begin(), town_edges[j].end());
}
ll ans = C0;
for (int mask = 1; mask < (1 << k); mask++) {
vector<Edge> current_edges = MST0_edges;
ll current_cost = C0;
int current_node_count = n;
ll total_c = 0;
for (int j = 0; j < k; j++) {
if (mask & (1 << j)) {
total_c += c[j];
vector<Edge> new_edges;
size_t idx1 = 0, idx2 = 0;
while (idx1 < current_edges.size() && idx2 < town_edges[j].size()) {
if (current_edges[idx1] < town_edges[j][idx2]) {
new_edges.push_back(current_edges[idx1++]);
} else {
new_edges.push_back(town_edges[j][idx2++]);
}
}
while (idx1 < current_edges.size()) new_edges.push_back(current_edges[idx1++]);
while (idx2 < town_edges[j].size()) new_edges.push_back(town_edges[j][idx2++]);
DSU dsu(n + k);
vector<Edge> selected_edges;
ll new_cost = 0;
int edges_needed = current_node_count;
for (const Edge& e : new_edges) {
if (dsu.unite(e.u, e.v)) {
selected_edges.push_back(e);
new_cost += e.w;
if (selected_edges.size() == edges_needed) break;
}
}
current_edges = selected_edges;
current_cost = new_cost;
current_node_count++;
}
}
ll total_cost = current_cost + total_c;
if (total_cost < ans) {
ans = total_cost;
}
}
cout << ans << endl;
return 0;
}
::::
T3
::::info[思考过程(783s/13min)]
首先,问题是关于谐音替换的。我们有n个字符串二元组(s_i1, s_i2),每个二元组中的两个字符串长度相等。然后有q个查询,每个查询给出两个字符串t1和t2,问有多少种方式通过一次替换(替换一个子串y为y',其中y必须等于某个s_i1,y'等于对应的s_i2)将t1变成t2。注意,替换方式不同当且仅当子串y的位置不同或使用的二元组i不同。
关键点:
每次替换只替换一个子串。
替换后必须恰好得到t2。
我们需要计算所有不同的替换方式。
观察:
替换操作可以看作是在t1中找到一个子串y,该子串等于某个s_i1,然后将其替换为s_i2,结果等于t2。
由于替换后整个字符串变成t2,那么t1和t2必须在某些位置相同,某些位置不同。实际上,替换操作只改变了一个连续子串,所以t1和t2应该只在某个连续区间内不同,而且这个区间的长度必须与某个s_i1的长度相等?不一定是这样,因为替换后字符串长度不变(因为|s_i1|=|s_i2|),所以t1和t2的长度必须相等。否则,如果长度不等,那么肯定无法通过一次替换得到,因为替换不改变字符串长度。所以首先,如果|t1| != |t2|,那么答案肯定是0。
但题目说t1和t2是不同的字符串,所以长度可能相等?输入保证t1和t2不同,但没有明确说长度相等。不过,由于替换操作不改变字符串长度,所以如果|t1| != |t2|,那么确实无法通过一次替换得到t2。所以我们在处理每个查询时,先检查|t1|和|t2|是否相等,如果不相等,输出0。
现在假设|t1| = |t2| = L。
那么,替换操作发生在t1的某个区间[l, r]上,我们将这个子串y替换为y',得到t2。那么,在替换区间之外,t1和t2必须完全相同。也就是说,t1[0:l]必须等于t2[0:l],t1[r+1:]必须等于t2[r+1:]。而且,子串y必须等于某个s_i1,替换后的y'必须等于对应的s_i2,同时y'必须等于t2[l:r+1](因为替换后这个区间变成y')。
所以,对于每个查询,我们需要找到所有可能的位置[l, r]和二元组i,使得:
t1[0:l] == t2[0:l]
t1[r+1:] == t2[r+1:]
t1[l:r+1] = s_i1
t2[l:r+1] = s_i2
注意,由于替换操作只进行一次,所以整个字符串只有这个区间被改变。
因此,对于每个查询,我们需要枚举所有可能的位置l和r吗?但L可能很大,最多500万?但总L2是500万,所以每个查询的字符串长度可能很大,但总长度和是500万,所以平均每个查询的字符串长度可能很小?但最坏情况下,可能有一个很长的字符串。
实际上,L2是∑|t_j1| + |t_j2| ≤ 5e6,所以所有查询字符串的总长度是5e6,因此每个查询的平均字符串长度大约是5e6 / (2 * q) = 5e6 / (4e5) = 12.5,所以大部分查询的字符串长度较短。但n和q最大为200000,所以我们需要高效的方法。
另一种思路:我们预先处理所有二元组,然后对于每个查询,我们如何快速找到满足条件的替换?
注意,替换要求t1和t2在区间外相同,所以实际上,我们可以先找到t1和t2的最长公共前缀(LCP)和最长公共后缀(LCS)。设lcp为最长公共前缀的长度,lcs为最长公共后缀的长度。那么,替换必须发生在区间[l, r]其中l从lcp开始,r从L-lcs-1开始?实际上,如果前缀匹配到位置l-1,后缀匹配从位置r+1开始,那么l必须大于等于lcp?不,严格来说,前缀必须匹配直到l-1,所以l必须小于等于lcp?让我们定义:
设前缀匹配直到位置p-1,即t1[0:p] == t2[0:p],但t1[p] != t2[p]?实际上,由于只有一段连续区间被改变,所以改变区间必须覆盖所有不匹配的位置。也就是说,t1和t2的不匹配必须是一个连续区间?是的,因为只改变了一个子串。所以,如果我们比较t1和t2,它们必须只在某个连续区间内不同,而且这个区间就是被替换的区域。
因此,对于t1和t2,我们可以先检查它们是否只有一个连续区间不同?如果是,那么这个区间就是候选的替换区间。但可能有多段不同吗?如果有多段不同,那么一次替换无法实现,因为一次替换只能改变一个连续区间。所以,对于每个查询,我们首先检查t1和t2是否只有一个连续区间不同?如果是,那么这个区间的长度设为len,那么我们需要检查是否存在二元组i,使得s_i1等于t1的这个子串,s_i2等于t2的这个子串。
但注意,替换操作允许使用任何二元组,只要子串y等于s_i1,替换为s_i2后等于t2的这个子串。所以,对于这个候选区间,我们只需要统计所有二元组i满足s_i1等于t1的子串且s_i2等于t2的子串。
但是,可能有多于一个候选区间吗?不,因为只有一个连续区间被改变,所以候选区间是唯一的?不,实际上,可能有很多不同的位置进行替换,但前提是替换后整个字符串变成t2。但注意,替换操作只改变一个子串,所以如果我们有两个不同的位置进行替换,那么它们对应的区间必须不同?是的。但有可能多个不同的区间替换后都得到t2吗?例如,t1和t2可能有多段不同,但一次替换只能改变一段,所以如果有多段不同,那么一次替换无法得到t2。因此,对于一次替换来说,t1和t2必须只有一个连续区间不同?是的,因为如果有多段不同,那么需要多次替换,但问题只允许一次替换。
所以,对于每个查询,我们首先检查t1和t2是否只有一个连续区间不同?如果是,那么设这个区间为[l, r],那么我们需要统计所有二元组i满足s_i1 == t1[l:r+1] and s_i2 == t2[l:r+1]。但注意,二元组i可能多个都有相同的s_i1和s_i2?是的,所以我们需要统计所有这样的二元组。
但是,还有另一种可能性:即使只有一个连续区间不同,但可能这个区间可以通过多个不同的二元组替换?是的,因为不同的二元组i可能具有相同的s_i1和s_i2?但二元组是不同的,所以即使s_i1和s_i2相同,不同的i也算不同的替换。
此外,还有可能:同一个区间,使用不同的二元组i,但二元组i要求s_i1等于子串,所以如果多个二元组有相同的s_i1和s_i2,那么它们都算。
但问题在于:是否可能存在多个不同的区间替换后都得到t2?例如,在t1中,可能有多个位置子串y等于某个s_i1,而且替换后都得到t2?但前提是替换后整个字符串必须等于t2。所以,对于每个候选区间,我们必须要求替换后整个字符串等于t2。也就是说,对于区间[l, r],替换后,除了这个区间,其他部分必须与t2相同,而且替换后的区间必须等于t2的区间。所以,对于每个区间[l, r],我们要求:
t1[0:l] == t2[0:l]
t1[r+1:] == t2[r+1:]
存在二元组i,使得s_i1 = t1[l:r+1] and s_i2 = t2[l:r+1]
那么,对于每个查询,我们需要找到所有满足条件的区间[l, r]和二元组i?但注意,对于同一个区间[l, r],可能有多个二元组i满足条件,所以贡献为满足的二元组个数。
但区间[l, r]可能有很多个吗?理论上,只要满足前后缀匹配,而且子串t1[l:r+1]等于某个s_i1,同时t2[l:r+1]等于对应的s_i2,那么就是一个有效的替换。
但问题在于,t1和t2可能只有一个连续区间不同,所以候选区间是固定的?不,不一定。考虑以下情况:t1和t2完全相等?但题目说t1和t2不同,所以不可能完全相等。那么,它们至少有一个位置不同。但可能多个区间替换后都能得到t2吗?例如,t1 = "abc", t2 = "adc",二元组有("b","d"),那么替换位置[1,1]是有效的。但还有别的区间吗?如果我们替换整个字符串?但整个字符串"abc"必须等于某个s_i1,但s_i1可能不等于"abc",所以不一定。所以,可能有多于一个候选区间吗?
让我们看样例1:第一个查询,t1="xabcx", t2="xadex",有两个替换方式:一个是替换整个字符串(使用二元组1),另一个是替换子串"bc"为"de"(使用二元组3)。所以有两个候选区间:一个是[0,4](整个字符串),另一个是[2,3](子串"bc")。所以确实有多个候选区间。
因此,对于每个查询,我们需要找到所有可能的区间[l, r],使得:
t1[0:l] == t2[0:l]
t1[r+1:] == t2[r+1:]
存在二元组i,使得s_i1 = t1[l:r+1] and s_i2 = t2[l:r+1]
然后,对于每个这样的区间,我们统计有多少个二元组i满足条件3。
那么,如何高效地找到所有这样的区间?由于总字符串长度和是5e6,我们可以对每个查询遍历所有可能的区间?但区间数量是O(L^2),对于长字符串不可行。
我们需要更高效的方法。
注意,条件1和2意味着区间[l, r]必须覆盖所有不匹配的位置。设不匹配的连续区间为[A, B],那么对于任何候选区间[l, r],它必须包含[A, B]?因为如果[l, r]没有包含所有不匹配点,那么有些点没有被改变,但这些点在不匹配,所以替换后这些点还是不同,因此整个字符串不会等于t2。所以,候选区间必须包含整个不匹配区间[A, B]。同时,候选区间不能改变匹配点?不,它可以改变匹配点吗?注意,如果改变了匹配点,那么原来匹配的点可能变得不匹配?但替换后要求整个字符串等于t2,所以如果我们改变了一个匹配点,那么替换后这个点必须变成t2的对应点,但原来这个点已经匹配,所以如果改变它,那么替换后这个点可能不匹配?不对,因为替换后这个点变成了y'的一部分,而y'必须等于t2的对应区间,所以只要y'等于t2的区间,那么整个字符串就匹配。所以,候选区间可以扩展到一个更大的区间,只要这个区间的替换后等于t2的对应区间。
但前提是,在区间外,t1和t2必须匹配。所以,候选区间[l, r]必须满足:
l <= A and r >= B
而且,对于所有位置 outside [l, r], t1和t2匹配。
所以,l可以从0到A,r可以从B到L-1?但l和r是相关的,因为区间长度必须等于某个s_i1的长度?不,因为每个二元组有固定的长度,设对于二元组i,长度len_i = |s_i1|。所以对于候选区间[l, r],长度len = r-l+1必须等于某个len_i,而且s_i1必须等于t1[l:l+len],s_i2必须等于t2[l:l+len]。
所以,实际上,候选区间的长度是固定的,由二元组决定。因此,我们不可能枚举所有区间,而是应该考虑所有二元组i,然后检查对于二元组i,是否存在位置l,使得:
t1[l:l+len_i] = s_i1
t2[l:l+len_i] = s_i2
t1[0:l] = t2[0:l]
t1[l+len_i:] = t2[l+len_i:]
也就是说,对于每个二元组i,我们可以检查它是否可以在t1的某个位置l进行替换,使得替换后得到t2。
那么,对于每个查询,我们枚举所有二元组i?但n最大200000,q最大200000,总枚举量是4e10,不可行。
我们需要更好的方法。
另一种思路:预处理所有二元组,将它们存储在一个哈希表中,键为(s_i1, s_i2),值为出现次数?但注意,不同的二元组可能有相同的(s_i1, s_i2),所以我们需要统计每个(s_i1, s_i2)对的出现次数。
然后,对于每个查询(t1, t2),我们需要找到所有位置l,使得存在二元组(s_i1, s_i2)满足:
s_i1 = t1[l:l+len] and s_i2 = t2[l:l+len] for some len
而且前后缀匹配。
但len是变化的,所以我们需要考虑所有可能的长度。
由于总字符串长度和是5e6,我们可以对每个查询,遍历所有可能的位置l吗?位置l的数量是L,L是当前查询的字符串长度,但所有查询的字符串总长度是5e6,所以如果我们对每个查询遍历所有位置l,总工作量是5e6,但对于每个位置l,我们需要检查是否存在二元组(s_i1, s_i2)使得s_i1等于t1从l开始的长为len的子串,s_i2等于t2从l开始的长为len的子串,而且前后缀匹配。
但前后缀匹配的条件是:t1[0:l] == t2[0:l] and t1[l+len:] == t2[l+len:]。所以,对于固定的l和len,我们需要检查前后缀匹配,以及子串匹配。
但len是来自二元组的,所以我们不能枚举所有len,因为len可能很多。
我们可以预处理所有二元组的长度,然后对于每个长度,我们存储所有(s_i1, s_i2)对?但长度种类可能很多,最多可能有多少种长度?由于总L1是5e6,所以长度种类不会超过O(sqrt(5e6))?但实际可能很多。
Alternatively,我们可以对二元组按长度分组,然后对于每个查询,我们只考虑那些长度len不超过L的二元组?但长度组数可能很多,而且对于每个长度,我们需要检查每个位置l,这样也不高效。
另一个想法:使用字符串哈希快速比较子串。
我们可以预先计算t1和t2的哈希值,然后对于每个二元组i,我们可以在t1中寻找s_i1的出现位置?但这样对于每个二元组i,我们需要在t1中匹配s_i1,然后检查在出现位置l,是否满足前后缀匹配以及s_i2等于t2的对应子串。
但如何在t1中寻找s_i1的出现位置?如果对每个查询都做,那么对于每个查询,我们需要处理n个二元组,不可行。
我们需要逆转思维:预处理所有二元组,然后对于查询,我们利用哈希来快速检查。
设H(s)是一个字符串的哈希函数。
对于每个查询(t1, t2),我们首先计算t1和t2的哈希值,然后计算它们的前缀哈希和后缀哈希。
然后,我们想知道对于每个可能的长度的二元组,是否在位置l出现。
但二元组有200000个,而查询也有200000个,所以我们不能枚举所有二元组。
我们可以将所有二元组(s_i1, s_i2)存储在一个哈希表G中,键为(H(s_i1), H(s_i2)),值为计数。但这样,对于查询,我们还需要知道子串的哈希值。
对于查询中的t1和t2,我们可以在O(L)时间内计算出所有子串的哈希值吗?但L是当前字符串长度,而且总L2是5e6,所以我们可以对每个查询计算出所有可能子串的哈希值?但子串数量是O(L),因为长度是固定的?不,长度是变化的。
实际上,对于每个位置l,我们只关心那些长度len使得存在二元组具有长度len,而且s_i1等于t1[l:l+len] and s_i2等于t2[l:l+len]。所以,如果我们知道所有二元组的长度集合,那么对于每个长度len,我们可以在t1和t2上滑动窗口计算哈希值,然后查询哈希对(H(t1[l:l+len]), H(t2[l:l+len]))是否在G中。
但长度len的种类数可能很多,而且对于每个长度len,我们需要滑动窗口,总工作量是O(∑_{len} L) = O(L * number_of_len)),这可能会很大。
由于总L2是5e6,但长度种类可能很多,我们不能枚举所有长度。
另一种思路:注意到,二元组的字符串总长度L1是5e6,所以我们可以将所有的s_i1和s_i2建成一个AC自动机?或者使用其他字符串匹配结构。
考虑以下:我们只关心那些在t1中出现的s_i1,而且要求对应的s_i2等于t2的对应子串。所以,我们可以用t1作为文本,将所有s_i1作为模式串放入AC自动机中,然后匹配t1,得到所有出现位置l和对应的二元组i。然后对于每个出现位置l,我们检查:
t1[0:l] == t2[0:l]吗?
t1[l+len_i:] == t2[l+len_i:]吗?
t2[l:l+len_i] == s_i2吗?
如果都满足,那么这是一个有效的替换。
那么,对于每个查询,我们如何快速做到这一点?如果我们对每个查询都构建AC自动机,那么总代价很高,因为q可能200000,而总文本长度是5e6,但构建AC自动机对于一组模式串的代价是O(L1),而L1是5e6,但如果我们对每个查询都构建,总代价是5e6 * q = 1e12,不可行。
所以,我们不能对每个查询构建AC自动机。
那么,我们能否预处理所有二元组到一个AC自动机中,然后对于每个查询的t1,我们通过AC自动机匹配得到所有出现位置?但问题在于,二元组有n个,模式串总长度L1=5e6,所以我们可以构建一个AC自动机包含所有s_i1。然后对于每个查询字符串t1,我们用它匹配AC自动机,得到所有出现位置和对应的模式串i。然后对于每个出现位置l和模式串i,我们检查上述条件。
这样,对于每个查询,匹配t1的时间是O(|t1| + number_of_occurrences)。但number_of_occurrences可能很大吗?由于模式串总长度5e6,但出现次数可能很多,但总查询字符串长度和是5e6,所以总匹配时间是可以接受的?但每个查询的出现次数可能很多,因为一个t1中可能出现很多模式串。
实际上,最坏情况下,一个t1中可能出现所有模式串吗?如果t1是aaa...aaa,而模式串有很多个a的子串,那么出现次数可能很多。但总出现次数可能达到O(|t1| * n)?不,通过AC自动机,我们可以得到所有出现位置,但出现位置的数量是O(|t1|)吗?不,因为每个位置可能匹配多个模式串,所以出现次数可能很多。例如,如果模式串有"a", "aa", "aaa", ...,那么在一个长字符串中,出现次数可能是指数级的?但模式串总长度5e6,所以模式串的数量是n=200000,但每个模式串的长度不会太长,所以出现次数不会太多?实际上,出现次数的总和可能很大,因为一个长字符串可能包含很多模式串。
但总查询字符串长度和是5e6,所以如果我们对每个查询匹配AC自动机,然后收集所有出现位置,那么总出现次数可能很大,可能达到5e6 * 平均模式串数量?但通过AC自动机,我们可以在匹配时输出所有出现,但最坏情况下,出现次数可能与文本长度乘以模式串数量成正比?这不可接受。
我们需要更好的方法。
另一种想法:由于替换要求前后缀匹配,我们可以先对于每个查询求出t1和t2的LCP和LCS。设LCP = p, LCS = s,那么候选区间必须满足 l <= p and r >= L-s-1? 实际上,因为前缀匹配直到p-1,所以 l must be <= p? 不,如果 l > p,那么位置p在区间外,但t1[p] != t2[p],所以不行。因此, l must be <= p? 实际上,位置p必须被覆盖,所以 l <= p and r >= p? 同样,后缀方面, r >= L-s-1? 设不匹配区间为 [A, B],那么 A = p, B = L-s-1? 因为从位置p开始不匹配,直到位置L-s-1结束不匹配?所以候选区间必须覆盖 [A, B] = [p, L-s-1]。
所以,候选区间 [l, r] 必须满足 l <= p and r >= L-s-1。
而且,区间长度 len = r-l+1 must be exactly the length of some binary group.
所以,对于每个二元组 i with length len_i, 我们要求 l such that:
l <= p
l + len_i - 1 >= L-s-1
t1[l:l+len_i] = s_i1
t2[l:l+len_i] = s_i2
所以,对于每个二元组 i, l 必须满足 l <= p and l >= L-s-1 - len_i + 1? 从 r = l+len_i-1 >= L-s-1, 所以 l >= L-s-1 - len_i + 1。
所以 l 的范围是 [ max(0, L-s-1 - len_i + 1), min(p, L-len_i) ]? 因为 l must be <= L-len_i.
然后,对于每个二元组 i,我们检查在这个 l 范围内,是否有 l 使得 t1[l:l+len_i] = s_i1 and t2[l:l+len_i] = s_i2。但 l 的范围可能很大,我们不能对每个二元组 i 都检查。
我们可以反过来:对于每个查询,我们只考虑那些长度 len_i >= (L-s-1 - p + 1) 的二元组?因为区间必须覆盖 [p, L-s-1],所以 len_i >= (L-s-1 - p + 1) = B-A+1。
设 min_len = B-A+1.
然后,对于每个二元组 i with len_i >= min_len, 我们检查是否存在 l in [ L-s-1 - len_i + 1, p ] such that the conditions hold.
但如何快速检查?我们可以用字符串哈希。对于每个查询,我们预先计算 t1 和 t2 的哈希值。然后对于每个二元组 i,我们计算 H(s_i1) and H(s_i2),然后检查对于 l in [ low, high ],是否有 H(t1[l:l+len_i]) = H(s_i1) and H(t2[l:l+len_i]) = H(s_i2)。但区间 [ low, high ] 可能很大,如果我们对每个二元组 i 都检查,代价可能很高。
由于二元组 i 的数量可能很多,而且 len_i >= min_len 的二元组可能很少? min_len 可能很大,所以符合条件的二元组 i 可能很少。
例如,如果 min_len = 1000,那么只有长度 >=1000 的二元组才被考虑,而这样的二元组可能很少,因为总 L1=5e6,所以长字符串的数量不会很多。
所以,我们可以预处理二元组,按长度排序,然后对于每个查询,我们只考虑长度 >= min_len 的二元组 i,然后对于每个这样的 i,我们检查 l 的范围是否有效,以及哈希值是否匹配。
但 l 的范围 [ low, high ] 可能包含多个 l,但我们只需要知道是否存在至少一个 l?不,我们需要统计有多少个 l 满足条件?不,对于二元组 i,如果它在多个 l 处满足条件,那么每个 l 都会贡献一次替换?是的,因为位置不同。
所以,对于二元组 i,它在 t1 中可能出现多次,但在我们的 l 范围内,可能出现多次。所以,我们需要统计在 l 范围内,二元组 i 的出现次数。
因此,对于每个二元组 i,我们想知道在 t1 中, s_i1 出现在哪些位置 l,而且 l 在 [ low, high ] 范围内,而且同时 t2 的对应子串等于 s_i2。
所以,如果我们有所有二元组 i 的 s_i1 在 t1 中的出现位置,那么我们可以快速统计。
但如何快速得到这些出现位置?我们可以预先构建一个 AC自动机对于所有 s_i1,然后对于每个查询 t1,我们匹配 AC自动机,得到每个 s_i1 的出现位置。然后,对于每个查询,我们只考虑那些长度 >= min_len 的二元组 i,然后根据出现位置统计在 [ low, high ] 内的出现次数。
但出现位置可能会很多,但我们可以预先存储每个 s_i1 的出现位置在 t1 中吗?不,因为 t1 是查询字符串,我们无法预先知道。
所以,对于每个查询,我们匹配 AC自动机,得到所有出现位置 (l, i),然后对于每个出现 (l,i),我们检查:
l >= low_i and l <= high_i, where low_i = L-s-1 - len_i + 1, high_i = p
t2[l:l+len_i] = s_i2
然后统计满足条件的出现次数。
这里 low_i 和 high_i 依赖于二元组 i 的长度 len_i 和查询的 L, s, p。
所以,对于每个查询,步骤如下:
计算 t1 和 t2 的长度 L,如果 L != |t2|,输出 0。
计算 t1 和 t2 的最长公共前缀 p:即最大的 p such that for all i<p, t1[i]==t2[i]。
计算 t1 和 t2 的最长公共后缀 s:即最大的 s such that for all i>L-s-1, t1[i]==t2[i]。
如果 p + s < L - 1? 实际上,如果不匹配区间是 [p, L-s-1],那么如果 p + s >= L,那么没有不匹配?但 t1 != t2,所以 p + s < L. 而且不匹配区间必须连续?如果有多段不匹配,那么 p + s < L-1? 实际上,如果只有一段不匹配,那么不匹配区间是 [p, L-s-1],而且 p + s = L - (B-A+1) ? 所以如果只有一段不匹配,那么 p + s = L - len_mismatch? 但 len_mismatch = B-A+1.
但如果有多个不连续的不匹配,那么一次替换无法实现,所以输出 0。所以,我们检查是否只有一段连续的不匹配?如何检查?我们可以计算不匹配的区间:从 p 开始,到 L-s-1 结束,然后检查中间是否全部不匹配?即检查 t1[p:L-s] 和 t2[p:L-s] 是否完全不一样?不,我们只需要检查从 p 到 L-s-1 之间是否有匹配的点?实际上,如果从 p 到 L-s-1 之间有一个点匹配,那么说明有多段不匹配?因为从 p 开始不匹配,然后后来匹配了,然后又不匹配,所以有多段。因此,要只有一段不匹配,必须要求从 p 到 L-s-1 之间所有的 i, t1[i] != t2[i]? 但也不必要,因为如果中间有匹配点,但替换区间覆盖了整个区域,那么替换后这些匹配点可能被改变?但替换后要求这些点变成 t2,所以如果这些点原来匹配,替换后可能变得不匹配?不,如果替换区间覆盖了一个匹配点,那么替换后这个点可能变成新的字符,但如果这个新的字符与 t2 相同,那么没问题。所以,实际上,替换区间可以覆盖匹配点,只要替换后整个区间等于 t2 的区间。所以,没有必要要求不匹配区间连续?实际上,替换区间必须覆盖所有不匹配点,但可以覆盖额外的匹配点,只要替换后这些匹配点变成 t2 的对应点即可。所以,替换区间必须包含所有不匹配点,但不必连续不匹配。
因此,对于 t1 和 t2,我们定义集合 M = { i | t1[i] != t2[i] }。那么一次替换能够实现 t1->t2 当且仅当存在一个区间 [l, r] 和一个二元组 i 使得:
M ⊆ [l, r]
t1[l:r+1] = s_i1
t2[l:r+1] = s_i2
所以,对于查询,我们首先找到 M,即所有不匹配的位置。如果 M 为空,那么 t1=t2,但题目说 t1!=t2,所以 M 非空。然后,我们要求 M 是一个连续区间?不,M 可能不连续?如果 M 不连续,那么一次替换只能改变一个连续区间,所以如果 M 不连续,那么无法一次替换实现,因为改变一个连续区间无法覆盖不连续的不匹配点。因此,一次替换能够实现的前提是 M 是一个连续区间。
所以,我们检查 M 是否连续?如果是,设 A = min(M), B = max(M),那么候选区间必须覆盖 [A, B]。然后 proceed。
所以步骤:
如果 |t1| != |t2|, return 0.
找到所有不匹配的位置 M。如果 M 不是连续区间, return 0.
设 A = min(M), B = max(M).
计算最长公共前缀 p = A? 实际上, p = A, because for i<A, t1[i]==t2[i]? 是的,因为 A 是第一个不匹配点。
计算最长公共后缀 s = L - B - 1? 因为对于 i>B, t1[i]==t2[i]? 是的。
然后,对于每个二元组 i,设 len_i = |s_i1|.
候选 l 的范围是 [ l_low, l_high ] where l_low = B - len_i + 1, l_high = A? wait, from covering [A,B], we require l <= A and r>=B, so l <= A and l+len_i-1>=B, so l >= B - len_i + 1.
So l must be in [ B-len_i+1, A ].
但 l must be non-negative and l+len_i-1 <= L-1, so l <= L-len_i.
所以 l 的范围是 [ max(0, B-len_i+1), min(A, L-len_i) ].
然后,对于二元组 i,如果 len_i < (B-A+1), then no l can cover [A,B] because the interval length is less than B-A+1, so skip.
对于二元组 i with len_i >= B-A+1, we consider l in [ low, high ] where low = max(0, B-len_i+1), high = min(A, L-len_i).
然后,对于每个 such l in this range, we check whether t1[l:l+len_i] == s_i1 and t2[l:l+len_i] == s_i2. If true, then count one.
然后,总的替换数量就是所有这样的 (l,i) 的对数。
现在,如何高效地执行步骤10对于所有二元组 i?
由于二元组 i 的数量可能很多,但 len_i >= B-A+1 的二元组 i 可能很少,而且 l 的范围可能很小,因为 low and high 可能 close。
但如何快速知道对于二元组 i,在 l 范围内有多少个 l 满足条件?我们需要知道 s_i1 在 t1 中出现的位置 within [ low, high ],而且同时 t2 的对应子串等于 s_i2。
我们可以用字符串哈希:预先计算 t1 和 t2 的哈希值,然后对于每个二元组 i,我们计算 H1 = H(s_i1), H2 = H(s_i2),然后对于 l in [ low, high ],我们检查 H(t1[l:l+len_i]) == H1 and H(t2[l:l+len_i]) == H2。但枚举 l 的范围可能会很慢,如果范围很大。
由于范围 [ low, high ] 的长度是 high - low + 1 = min(A, L-len_i) - max(0, B-len_i+1) + 1. 由于 len_i >= B-A+1, so B-len_i+1 <= A - (len_i - (B-A+1)) <= A, so the range might be small? Not necessarily, if len_i is large, then low = B-len_i+1 might be very small, and high = A might be large, so the range could be from 0 to A, which is A+1, which can be up to L. So in the worst case, the range might be O(L) for each binary group i, and if there are many binary groups i with len_i >= B-A+1, then total work could be O(L * number_of_i) which might be large.
例如,如果 A=0, B=L-1, then min_len = L, so only binary groups with len_i = L are considered. How many such binary groups? Probably few. So the number of i with len_i >= L might be very small, since L can be large, but the number of binary groups with length L is limited by the fact that total L1 is 5e6.
所以,对于每个查询, number of i with len_i >= B-A+1 可能很少。
因此,我们可以这样做:
预处理所有二元组,并按长度分组,存储每个长度对应的二元组列表,每个二元组包含 (s_i1, s_i2) 和其哈希值。
对于每个查询,计算 A and B.
然后,对于每个长度 len >= (B-A+1) 且 len <= L,从预处理中获取该长度的所有二元组 i。
对于每个这样的二元组 i,计算 l 的范围 [ low, high ] = [ max(0, B-len+1), min(A, L-len) ].
然后,对于每个 l in [ low, high ],检查哈希值是否匹配。
但枚举 l 的范围可能代价高,如果范围很大。不过,由于 len 很大,范围 [ low, high ] 可能很小?因为 low = B-len+1, high = A, and since len >= B-A+1, then B-len+1 <= A, so the range is from low to A, and the length of the range is A - low + 1 = A - (B-len+1) + 1 = A - B + len - 1 + 1 = len - (B-A) - 1 + 1? Let me compute: the number of l is: high - low + 1 = min(A, L-len) - max(0, B-len+1) + 1.
由于 len >= B-A+1, so B-len+1 <= A, so low = B-len+1, high = min(A, L-len). So the number of l is: min(A, L-len) - (B-len+1) + 1.
如果 A <= L-len, then number = A - (B-len+1) + 1 = A - B + len - 1 + 1 = len - (B-A).
如果 A > L-len, then number = L-len - (B-len+1) + 1 = L-len - B + len -1 +1 = L-B.
由于 B = L-s-1, so L-B = s+1, which might be small if s is small.
所以,范围的长度是 min( len - (B-A), L-B ) = min( len - (B-A), s+1 ).
由于 len >= B-A+1, so len - (B-A) >= 1, so the range length is at least 1, at most s+1 or len - (B-A). But len - (B-A) might be large if len is large, but then L-B might be small. So in practice, the range might be small.
因此,我们可以直接枚举 l 在 [ low, high ] 范围内,对于每个二元组 i。
但总工作量是多少?对于每个查询,我们考虑的所有二元组 i 的数量乘以范围长度。由于总查询字符串长度和是5e6,而且二元组按长度过滤后数量不会很多,所以总工作量应该可以接受。
我们可以用双哈希避免碰撞。
实施方案:
预处理:
读取 n, q。
存储所有二元组到一个列表 pairs[],每个元素是 (s1, s2, len, h1, h2),其中 h1 = hash(s1), h2 = hash(s2)。
Group the pairs by length: create a map length_map, where key is length, value is a list of (h1, h2) for pairs with that length.
对于每个查询:
读取 t1, t2。
L1 = len(t1), L2 = len(t2),如果 L1 != L2,输出0。
计算不匹配集合 M:遍历 i from 0 to L1-1, if t1[i] != t2[i], record i。
如果 M 为空,输出0?但 t1!=t2,所以 M 非空。
检查 M 是否连续:如果 M 中所有索引是连续的,即 max(M) - min(M) + 1 == |M|,那么连续,否则输出0。
A = min(M), B = max(M)
min_len = B - A + 1
计算 t1 和 t2 的哈希值使用双哈希。设 base1, base2, mod1, mod2。
预计算 t1 和 t2 的前缀哈希数组 H11, H12 for t1, H21, H22 for t2。
初始化答案 = 0。
对于每个长度 len in range(min_len, L1+1): // only consider len from min_len to L1
如果 length_map 中存在 len,则获取列表 L = length_map[len]
计算 low = max(0, B - len + 1), high = min(A, L1 - len)
如果 low > high,跳过这个 len。
对于每个二元组 (h1, h2) in L:
对于 l in [low, high]:
计算 hash1_t1 = get_hash(H11, H12, l, l+len-1) for t1
计算 hash1_t2 = get_hash(H21, H22, l, l+len-1) for t2
如果 hash1_t1 == h1 and hash1_t2 == h2:
答案 += 1
输出答案。
但注意,同一个二元组 i 可能出现多次在列表中?不,我们在 grouping 时,对于每个长度,我们存储了所有二元组的 (h1,h2),但如果有多个二元组具有相同的 (s1,s2) 和长度,那么它们会有相同的 (h1,h2),所以我们在列表中会有多个相同的 (h1,h2)?是的,所以我们需要在 grouping 时存储计数?不,我们存储的是二元组的哈希值,但不同的二元组可能具有相同的 s1和 s2,所以我们应该存储 (h1,h2) 的出现次数。所以在预处理时,对于每个长度 len,我们存储一个字典:键为 (h1,h2),值为出现次数。
然后,在查询时,对于每个 (h1,h2) 在列表中,我们得到计数 c,然后对于每个 l 满足条件,我们加 c。
这样,我们不需要枚举每个二元组 i,而是枚举不同的 (h1,h2) 组合。
但注意,不同的二元组 i 可能具有相同的 s1和 s2,所以它们应该被视为不同的替换,所以我们需要统计次数。
所以,在预处理时,对于每个长度 len,我们有一个字典 counter_len,键 (h1,h2) 的值是出现次数。
在查询时,对于长度 len,我们获取 counter_len,然后对于每个 l in [low, high],我们计算 (H_t1(l, l+len-1), H_t2(l, l+len-1)),然后如果这个键在 counter_len 中,则答案 += counter_len[键]。
这样,我们不需要枚举所有的 (h1,h2),而是枚举 l 的范围,然后对于每个 l,我们计算哈希对,然后查字典。
这样,对于每个长度 len,我们只需要枚举 l 的范围,然后查字典一次 per l。
所以,对于每个长度 len,工作量是 O( range_size ),然后总工作量是所有 len 的 range_size 之和。
由于 len 从 min_len 到 L1,而且对于每个 len,范围大小是 range_size = min(A, L1-len) - max(0, B-len+1) + 1。
所有 len 的 range_size 之和是多少? len 从 min_len 到 L1, range_size = number of l for this len.
但所有 len 的 l 的总数是多少?实际上,对于每个 l,它可能对应多个 len?不,在这里对于每个 len,我们考虑不同的 l。
但 note that for a fixed l, the len must be such that min_len <= len <= L1, and l is in [ low, high] for this len. But l and len are related.
实际上,如果我们考虑所有 len,那么总的 l 的枚举次数是 sum_{len=min_len}^{L1} [ number of l for this len ].
number of l for this len = high - low + 1 = min(A, L1-len) - max(0, B-len+1) + 1.
由于 min(A, L1-len) <= A, and max(0, B-len+1) >= B-len+1, so number of l <= A - (B-len+1) + 1 = len - (B-A).
所以 sum_{len=min_len}^{L1} (len - (B-A)) = sum_{len=min_len}^{L1} len - (B-A)*(L1 - min_len + 1).
这是一个等差数列求和,所以总和大约是 O(L1^2)?最坏情况下 L1=10000,那么 L1^2=1e8,可能接受?但总查询字符串长度和是5e6,但 L1 是每个查询的字符串长度,所有查询的字符串长度和是5e6,所以最坏情况下,一个查询的字符串长度可能很大?例如,有一个查询字符串长度是5e6,那么 L1=5e6,那么枚举 len 从 min_len 到 L1,然后对于每个 len 枚举 l,那么工作量是 O(L1^2) = 2.5e13,不可接受。
所以,我们需要更高效的方法。
我们必须避免枚举所有 len 和 l。
另一种想法:注意候选 l 必须满足 l <= A and l >= B-len+1 for some len, but l must be such that the substring of t1 from l to l+len-1 has length len, and len is determined by the binary group.
Instead, we can consider all possible l that might be the start of a replacement. For each l, the length len must be at least (B-A+1) and at most L1-l, and must be such that the substring t1[l:l+len] must be equal to some s_i1 and t2[l:l+len] must be equal to s_i2. But then we need to know for each l, what are the possible len that satisfy the condition.
But note that for a fixed l, the len must be at least max(B-l+1, min_len) and at most L1-l? But from covering, we require l+len-1>=B, so len>= B-l+1. So for fixed l, len must be >= max(B-l+1, min_len) and <= L1-l.
Then, for fixed l, we want to count the number of binary groups i with len_i in [ max(B-l+1, min_len), L1-l ] such that s_i1 = t1[l:l+len_i] and s_i2 = t2[l:l+len_i].
How to do this quickly? We can use a hash table for each l? No.
We can use a two-dimensional problem?
I think the best approach is to use the AC automaton for all s_i1, and then for each query, match t1 to get all occurrences (l, i) with length len_i. Then, for each occurrence (l,i), we check if:
l <= A
l+len_i-1 >= B
t2[l:l+len_i] == s_i2
Then count these occurrences.
This way, we don't need to enumerate all l and len, but only the occurrences from AC automaton.
So steps for each query:
If |t1| != |t2|, return 0.
Find A and B from t1 and t2.
Match t1 against AC automaton to get all occurrences (l, i).
For each occurrence (l,i), let len = len_i.
If l <= A and l+len-1 >= B and t2[l:l+len] == s_i2, then count++.
Return count.
How to match t1 against AC automaton? We have built an AC automaton for all s_i1. The total length of patterns is 5e6, so AC automaton is feasible.
But then, for each query, we need to match t1, and the total length of t1 over all queries is 5e6, so the matching time is O(5e6 + number of occurrences).
The number of occurrences might be large? But the number of occurrences for all queries might be large, but the total patterns length is 5e6, and the total text length is 5e6, so the total number of occurrences might be within 5e6? Not necessarily, because one pattern can appear multiple times in one text.
However, in practice, the number of occurrences might be acceptable? Let me see: the total text length is 5e6, and the number of patterns is 200000, so the number of occurrences might be at most 5e6 * average number of patterns per position? But with AC automaton, the number of occurrences is at most the number of pattern matches, which can be O(5e6) if there are many short patterns.
For example, if there are many patterns of length 1, then each character in t1 will match as many patterns as there are patterns of length 1? So if there are 200000 patterns of length 1, then each character will match 200000 patterns? Then for a text of length 5e6, the number of occurrences would be 5e6 * 200000 = 1e12, which is too high.
So, to avoid this, we need to note that not all patterns will be matched at every position. But in worst-case, if all patterns are "a", then indeed every character will match all patterns that are "a", so number of occurrences would be |t1| * n, which is 5e6 * 200000 = 1e12, which is too high.
So, we cannot use AC automaton if we output all occurrences.
We need a better way.
Another idea: use hashing to quickly check for a given l and len whether the condition holds, but avoid enumerating all l and len.
From the condition, l must be in [0, A] and must have len such that l+len-1>=B. So for a given l, the minimum len is B-l+1. So for each l in [0, A], we consider len from B-l+1 to L1-l. Then we want to count the number of binary groups i with len_i = len such that s_i1 = t1[l:l+len] and s_i2 = t2[l:l+len].
So for each l, we can compute the required len: but len must be exactly the length of some binary group. So for each l, we can compute the hash of t1[l:l+len] and t2[l:l+len] for all len that are in the set of lengths of binary groups? But len varies.
For a fixed l, the string t1[l:] has many substrings, but we only care about those lengths that are in the binary groups.
So, if we precompute the set of lengths that appear in binary groups, and for each length, we have a hash table of (h1, h2) pairs, then for each l in [0, A], we can do the following:
For each len in the set of lengths that are between B-l+1 and L1-l, we compute the hash of t1[l:l+len] and t2[l:l+len] and then look up in the hash table for length len whether (h1, h2) is present.
But then for each l, we would need to iterate over all len in the set that are in [B-l+1, L1-l]. The number of len in the set may be large, and for each l, the number of len may be large, so total work would be O(A * number of len), which could be large.
Since A can be up to L1, and number of len can be up to the number of distinct lengths, which is at most 200000, then total work would be O(L1 * 200000) which is too high.
So, we need a different approach.
Let me change the order: for each binary group i, we know len_i. Then for each i, the condition on l is: l in [0, A] and l+len_i-1>=B, so l in [B-len_i+1, A] and l<=L1-len_i.
So, for each binary group i, the valid l are in [ low, high ] where low = max(0, B-len_i+1), high = min(A, L1-len_i).
Then, the condition for a given i and l is that the substrings match.
So, if we want to count the number of i and l such that the conditions hold, we can use a two-dimensional array? No.
We can use hashing to quickly check for a given i and l whether the substrings match, but then we need to know for which i and l the substrings match.
Notice that for a given i, the condition on the substring is that s_i1 must equal t1[l:l+len_i] and s_i2 must equal t2[l:l+len_i]. So, for a given i, the value of s_i1 and s_i2 are fixed, so we can precompute the hash of s_i1 and s_i2.
Then, for a given i, the set of l that satisfy the substring condition is simply the set of l where t1 has s_i1 starting at l and t2 has s_i2 starting at l.
So, if we know the set of l where t1 has s_i1, then we can intersect with [ low, high ].
How to get the set of l where t1 has s_i1? We can use AC automaton to find the occurrences of s_i1 in t1, but then we need to do this for each i? But then we are back to the AC automaton that outputs all occurrences.
But if we use AC automaton, we can create a data structure that, for each i, stores the occurrences of s_i1 in t1? But then for each query, we would need to know the occurrences for each i, which is expensive.
Perhaps we can use a different method: for each query, we precompute the hash of t1 and t2 for all possible l and len? No.
Another idea: use a rolling hash and then for each binary group i, we can determine the l in [ low, high ] by checking the hash of t1 and t2 at l. But then we would need to do this for each i, and the number of i may be large.
But note that for each i, the range [ low, high ] may be small, so we can try to do it for each i.
However, the number of i is n=200000, and for each query, we would need to process all i? That would be 200000 * q = 4e10, which is too high.
So, we must reduce the number of i per query.
How to reduce? We only i with len_i >= min_len. So, if we group i by len_i, and then for each query, we only consider i with len_i >= min_len, and then within that, we further reduce by checking the range [ low, high ].
But how many i have len_i >= min_len? It depends on min_len. If min_len is large, then few i will have len_i >= min_len.
In the worst case, min_len might be 1, so all i will be considered. So, if min_len=1, then we would have to process all i for each query, which is 200000 * q = 4e10, which is too high.
So, we need a better method.
Let me consider the special properties in the problem.
Special property A: q=1. So if q=1, then we can do an O(n) method for that one query.
Special property B: strings are only 'a' and 'b' with exactly one 'b'. So we can handle this specially.
For the general case, perhaps we can use the following:
Precompute a list of all binary groups i with their (s_i1, s_i2) and len_i.
For each query, we can use a hash set for the required substrings.
Notice that for the substitution to work, the substring of t1 from l to l+len-1 must be one of the s_i1, and the substring of t2 from l to l+len-1 must be the corresponding s_i2. So, for a given l and len, the pair ( substring1, substring2 ) must be in the set of binary groups.
So, if we precompute a set S of all pairs (s_i1, s_i2) with their lengths, but then for a query, we need to know for which l and len the pair ( t1[l:l+len], t2[l:l+len] ) is in S.
But then we need to enumerate l and len.
To avoid enumerating all l and len, we note that len must be at least min_len, and l must be in [0, A]. So for each l in [0, A], we can try to find all len such that the pair ( t1[l:l+len], t2[l:l+len] ) is in S. But len must be at least B-l+1.
For each l, the number of len to try is from B-l+1 to L1-l. This is still O(L1) per l, so total O(A * L1) = O(L1^2) per query.
So, if L1 is small, this is feasible. But if L1 is large, this is not.
Since the total L2 is 5e6, the maximum L1 for a query might be large, but the average L1 is small. So, we can use this method for small L1, and for large L1, we use the method that only considers i with large len.
But how to know if L1 is small? We can set a threshold. If L1 is less than 1000, then use the O(L1^2) method; otherwise, use the method that only considers i with len_i >= min_len.
For the method that only considers i with len_i >= min_len, we can then for each i, check the range [ low, high ] and then check the hashes for each l in that range. But if the range is large, then for each i, we might need to check many l.
But if L1 is large, then min_len = B-A+1 might be large, so the number of i with len_i >= min_len might be small, and for each i, the range [ low, high ] might be small because high = min(A, L1-len_i) and A might be small? But A is the first mismatch, so if L1 is large, A might be small? Not necessarily.
In the worst case, A might be L1-1, so if L1 is large, A might be large. But then B might be L1-1, so min_len = 1, so we have to consider all i. So for large L1 and A=L1-1, we have to consider all i, and for each i, the range [ low, high ] might be [ B-len_i+1, A ] = [ L1-1-len_i+1, L1-1] = [ L1-len_i, L1-1]. The number of l in this range is len_i? because from L1-len_i to L1-1, there are len_i l? But wait, l must be such that l+len_i-1 <= L1-1, so l <= L1-len_i. So if l must be <= L1-len_i, then in the range [ L1-len_i, L1-1] only L1-len_i is valid? because if l = L1-len_i, then l+len_i-1 = L1-1. If l = L1-len_i+1, then l+len_i-1 = L1, which is out of bounds. So actually, l must be <= L1-len_i. So high = min(A, L1-len_i) = L1-len_i if A is L1-1. So the range [ low, high ] = [ L1-1-len_i+1, L1-len_i ] = [ L1-len_i, L1-len_i ]? So only one l: l = L1-len_i.
So in this case, for each i, we only need to check one l.
So in general, for a given i, the number of l is at most 1 if A and L1-len_i are small? Not exactly, but in the case where A = L1-1, then high = L1-len_i, and low = B-len_i+1 = (L1-1) - len_i + 1 = L1-len_i. So only one l.
In the case where A is small, then high = A, which is small, so the range is small.
So, in practice, for each i, the number of l we need to check is small.
Therefore, we can do the following for each query:
If |t1| != |t2|, return 0.
Find A and B. If M is not continuous, return 0.
Precompute the hashes for t1 and t2.
For each binary group i from 1 to n:
len = len_i
if len < B-A+1, skip.
low = max(0, B-len+1)
high = min(A, L1-len)
if low > high, skip.
For l in [ low, high ]:
if get_hash(t1, l, l+len-1) == H1_i and get_hash(t2, l, l+len-1) == H2_i:
count++
Return count.
This will work if the number of i that have len >= min_len is small, and for each i, the number of l is small.
In the worst case, if min_len=1, then we have to process all i, and for each i, the number of l might be large? But from earlier analysis, the number of l for each i is at most min(A, L1-len) - max(0, B-len+1) + 1. If min_len=1, then for i with len=1, low = B-1+1 = B, high = min(A, L1-1). Since A and B are at most L1-1, then for len=1, low = B, high = A. But then if A < B, then low > high, so no l. So only if A >= B, then l from B to A. So the number of l is A-B+1. If A and B are close, then number of l is small. If A and B are far, then number of l could be large? But A and B are the first and last mismatch, so if A and B are far, then the string has a long range of mismatches, so min_len = B-A+1 is large, so for len=1, we have len < min_len, so we skip. So in the case where min_len=1, we have A and B must be close? because if min_len=1, then B-A+1=1, so A=B. So then for len=1, low = B-1+1 = B = A, high = min(A, L1-1) = A, so only one l: l=A.
So in the case where min_len=1, for each i with len=1, we only need to check l=A.
Similarly, for i with len>1, we have len>=2, but min_len=1, so we include them. For i with len=2, low = B-2+1 = B-1, high = min(A, L1-2). Since A=B, then low = A-1, high = A. So two l: l=A-1 and l=A. But then we need to check these l.
So for i with len=2, we need to check 2 l.
For i with len=3, low = A-2, high = A, so 3 l? But note: l must be such that l+len-1 <= L1-1. If L1 is large, then yes.
So in general, for i with len_i, the number of l is len_i - (B-A)? but since B-A=0, so number of l = len_i.
So if there are many i with large len_i, then the number of l to check could be large.
However, the number of i with large len_i is small because the total length of all s_i1 is 5e6. So the number of i with len_i > L0 for some L0 is at most 5e6 / L0.
For example, if we consider len_i > 1000, then number of i is at most 5000.
So in the worst case, if min_len=1, then the number of i with len_i>=1 is n=200000. For each i, the number of l to check is len_i. So the total work would be sum_{i} len_i = total length of s_i1 = 5e6. So actually, it's 5e6 per query? But then for q=200000, total work would be 5e6 * 200000 = 1e12, which is too high.
So, if min_len=1, then for each query, we would need to do 5e6 work? No, because the number of i is 200000, but the total length of s_i1 is 5e6, so the sum of len_i over i is 5e6. So if we process each i and for each i we do len_i work, then the total work per query is 5e6. So for one query, 5e6 is acceptable? But for 200000 queries, total work would be 5e6 * 200000 = 1e12, which is not acceptable.
So, we cannot do this for all queries.
Therefore, we need to use a different method for queries with small L1.
Let me define: if L1 is small, say L1 <= 1000, then we can use the O(L1^2) method: for each l in [0, A] and for each len in [B-l+1, L1-l] that is in the set of lengths, we check the hash of the substrings and then look up in the precomputed hash table for that length.
For L1 > 1000, we use the method that only considers i with len_i >= min_len, and then for each i, we check the l in [ low, high ] which should be small because min_len is large.
But for L1 > 1000, if min_len is small, then we have to consider many i? But if L1 > 1000 and min_len is small, then A and B must be close? because min_len = B-A+1. If min_len is small, then B-A is small, so A and B are close. Then for each i, the range [ low, high ] is from B-len_i+1 to A. Since A and B are close, the range might be small? For example, if A=B, then range is [ B-len_i+1, A] = [ A-len_i+1, A]. The number of l is len_i. So if len_i is large, then number of l is large. But then the number of i with large len_i is small.
So, in practice, the total work per query might be acceptable.
So, we can implement two methods:
Method 1: for L1 <= 1000.
Precompute a set of lengths that appear in binary groups.
For each length len in the set, precompute a hash table that maps (H1, H2) to count.
For the query, for each l in [0, A]:
for each len in the set such that len >= B-l+1 and len <= L1-l:
compute H1 = hash(t1[l:l+len])
compute H2 = hash(t2[l:l+len])
if (H1, H2) in the hash table for length len, then add count to answer.
Method 2: for L1 > 1000.
Precompute a list of binary groups i with len_i >= min_len.
For each such i:
low = max(0, B-len_i+1)
high = min(A, L1-len_i)
for l in [ low, high ]:
if hash(t1[l:l+len_i]) == H1_i and hash(t2[l:l+len_i]) == H2_i:
answer += 1
But in method 2, how do we get the list of binary groups i with len_i >= min_len? We can precompute a list of all binary groups sorted by len_i, and then for each query, we use binary search to get the ones with len_i >= min_len.
Since the number of i with len_i >= min_len may be small, this might be efficient.
Let me test with worst-case: if L1=1000, then method 1: L1=1000, A might be 500, then for each l, the number of len in the set might be the number of distinct lengths, which is at most 200000. Then total work would be 500 * 200000 = 100e6, which is acceptable for one query? But if there are many queries with L1=1000, then the total number of such queries might be limited by the total L2=5e6, so the number of queries with L1=1000 is at most 5e6 / 1000 = 5000. Then total work for method 1 would be 5000 * 100e6 = 500e9, which is too high.
So, we need to reduce the number of len in method 1.
In method 1, for each l, we don't need to consider all len in the set, but only len that are between B-l+1 and L1-l. The number of len in the set that are in this range may be small because the set of lengths is limited, and for each l, the range of len is [B-l+1, L1-l] which has length L1-B - (B-l+1) + 1? But the number of len in the set is the number of distinct lengths that fall into this range. Since the set of lengths has at most 200000 distinct lengths, but for a given l, the range of len may have only a few lengths? Not necessarily.
To make method 1 efficient, we can precompute an array of lengths that appear, and then for each l, we can quickly iterate over the lengths that are in [B-l+1, L1-l] by using a sorted list of lengths.
But then for each l, we need to go through the sorted list of lengths and find those that are in [B-l+1, L1-l]. The number of such lengths might be O(1) per l? No.
Since the number of distinct lengths is 200000, then for each l, we would need to consider 200000 lengths? No, because we can use binary search to find the lengths in the range. So for each l, we can do two binary searches to find the start and end of the range in the sorted list of lengths. Then, the number of lengths in the range might be small? It depends on the distribution of lengths.
If the lengths are spread out, then for a given l, the range [B-l+1, L1-l] might contain many lengths? For example, if B-l+1=1 and L1-l=1000, then if the sorted list of lengths contains many lengths between 1 and 1000, then the number might be large.
So, to avoid this, we can group the lengths by their value, and then for each l, we only consider the lengths that are in the range. But then the total work over all l would be the number of l times the number of lengths in the range. But the number of lengths in the range might be the same for all l? Not exactly.
Perhaps we can reverse the loops: for each length len in the set, we determine the l that are in [0, A] and [B-l+1, L1-l] for this len. For a fixed len, the l must be in [ low, high ] where low = max(0, B-len+1), high = min(A, L1-len). Then we can do the same as in method 2.
So actually, method 1 and method 2 are the same: for each len in the set, we consider l in [ low, high ].
So why not use the same method for all queries? That is, for each query, we iterate over all distinct lengths that are >= min_len, and for each length, we then iterate over l in [ low, high ] and then check the hash.
Then, the total work for a query is the sum over len of the number of l for that len.
How to compute the total work? The number of distinct lengths is M, and for each length, the number of l is number of l in [ low, high ].
The sum over len of the number of l is the total number of (l, len) pairs.
How many such pairs? For each l, the len must be in [ B-l+1, L1-l] and must be in the set of lengths. So the number of pairs is the number of l in [0, A] times the number of len in the set that are in [ B-l+1, L1-l].
Since the set of lengths is fixed, we can precompute the set of lengths.
But then the number of pairs might be large.
However, note that for a given l, the number of len that are in [ B-l+1, L1-l] is at most the number of lengths in the set that fall into this range. Since the set of lengths has M elements, the number for each l is at most M. So total pairs is A * M.
But A can be up to L1, and M can be up to 200000, so if L1=1000, then A=1000, and M=200000, then total pairs = 1000 * 200000 = 200e6, which is acceptable for one query? But then for many queries, the total might be high.
So, we need to reduce M for each query.
Notice that for a given query, the len must be at least min_len. So M can be reduced to the number of distinct lengths that are >= min_len.
So, if min_len is large, then M is small.
For example, if min_len=1000, then M might be small.
So, for each query, we can first determine min_len, then get the set of lengths that are >= min_len. Let M' be the number of such lengths.
Then, for each length in this set, we compute the number of l in [ low, high ].
Then the total work is M' * ( number of l per length )? But number of l per length is the number of l in [ low, high ] for that length.
Since M' is small, and for each length, the number of l is small, then total work is small.
So, we can use this method for all queries.
Steps for each query:
If |t1| != |t2|, return 0.
Find A and B. If M is not continuous, return 0.
min_len = B-A+1.
Let lengths_set = sorted list of distinct lengths that are >= min_len from the binary groups.
Precompute the hashes for t1 and t2.
For each len in lengths_set:
low = max(0, B-len+1)
high = min(A, L1-len)
if low > high, continue.
Let H_dict = precomputed hash table for length len. ( which maps (h1, h2) to count )
For l in [ low, high ]:
h1 = get_hash(t1, l, l+len-1)
h2 = get_hash(t2, l, l+len-1)
if (h1, h2) in H_dict, then answer += H_dict[(h1, h2)]
Output answer.
How to get the precomputed hash table for each length? We can precompute this for all lengths that appear.
Precomputation for the binary groups:
Create a map: length_map = {}
For each binary group i:
len = len_i
h1 = hash(s_i1)
h2 = hash(s_i2)
if length_map doesn't have len, then length_map[len] = {}
then length_map[len][(h1, h2)] += 1
Then, for each query, we need to get the lengths from length_map that are >= min_len.
We can precompute a sorted list of lengths that appear: sorted_lengths = sorted(length_map.keys())
Then for each query, we use binary search to find the start from min_len.
Then, for each len in sorted_lengths from min_len to max_len, we do the following.
Now, what is the total work for all queries? The total work for one query is the sum over len in [min_len, max_len] of the number of l in [ low, high ] for that len.
The number of l for a given len is at most ( high - low + 1 ) = min(A, L1-len) - max(0, B-len+1) + 1.
As before, this value is small.
So, we implement this.
Let me code accordingly.
We need to use double hashing to avoid collisions.
Choose two bases and two mods.
Code structure:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int base1 = 131;
const int base2 = 13131;
const int mod1 = 1e9+7;
const int mod2 = 1e9+9;
struct Hasher {
vector<ll> H1, H2;
vector<ll> pow1, pow2;
string s;
int n;
Hasher(string &str) {
s = str;
n = s.size();
H1.resize(n+1);
H2.resize(n+1);
pow1.resize(n+1);
pow2.resize(n+1);
pow1[0] = 1;
pow2[0] = 1;
for (int i=1; i<=n; i++) {
pow1[i] = (pow1[i-1] * base1) % mod1;
pow2[i] = (pow2[i-1] * base2) % mod2;
}
for (int i=0; i<n; i++) {
H1[i+1] = (H1[i] * base1 + s[i]) % mod1;
H2[i+1] = (H2[i] * base2 + s[i]) % mod2;
}
}
pair<ll,ll> get_hash(int l, int r) {
// l and r inclusive
ll hash1 = (H1[r+1] - H1[l] * pow1[r-l+1] % mod1 + mod1) % mod1;
ll hash2 = (H2[r+1] - H2[l] * pow2[r-l+1] % mod2 + mod2) % mod2;
return {hash1, hash2};
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
text
int n, q;
cin >> n >> q;
// Precompute length_map
map<int, map<pair<ll,ll>, int>> length_map;
vector<string> s1_list(n), s2_list(n);
for (int i=0; i<n; i++) {
string s1, s2;
cin >> s1 >> s2;
s1_list[i] = s1;
s2_list[i] = s2;
int len = s1.size();
Hasher H1(s1), H2(s2);
auto h1 = H1.get_hash(0, len-1);
auto h2 = H2.get_hash(0, len-1);
length_map[len][{h1.first, h1.second}]++; // wait, we need to store the pair (h1, h2) for the binary group?
// But note: for a binary group, we need to check that s_i1 matches t1's substring and s_i2 matches t2's substring.
// So when we store in length_map, we should store the pair ( hash(s_i1), hash(s_i2) ) for the binary group.
// So here, we should store an entry for length len with key (h1, h2) and value count.
// But in the code above, I stored only one hash for s1? I need to store both hashes for s1 and s2.
// So let me correct: we need to store the pair of hashes: ( hash(s_i1), hash(s_i2) ) as the key.
length_map[len][{h1.first, h1.second}]++; // This is wrong because we need to include h2.
// Correctly:
// We have hasher for s1 and hasher for s2.
// But hasher for s1 gives hashes for s1, and hasher for s2 gives hashes for s2.
// So we want to store the pair ( hash(s1), hash(s2) ) for the binary group.
// So let me define:
auto hash_s1 = H1.get_hash(0, len-1);
auto hash_s2 = H2.get_hash(0, len-1);
// Then store the pair of pairs: ( (hash_s1.first, hash_s1.second), (hash_s2.first, hash_s2.second) ) as the key? But then the key would be a tuple of four integers?
// Alternatively, we can combine the hashes: let me define a single hash for the pair (s1,s2) by hashing the string s1 and s2 together? But then we might lose the separate hashes.
// Since we will compare with t1 and t2 separately, we need to know the hash of s1 and the hash of s2 separately.
// So in length_map, for each length len, we want to store a mapping from ( hash1_s1, hash2_s1, hash1_s2, hash2_s2 ) to count? But that is four integers.
// Alternatively, we can use two pairs: let key = make_pair( make_pair(h1_s1, h2_s1), make_pair(h1_s2, h2_s2) ). But then we need to use a map with key of type pair<pair<ll,ll>, pair<ll,ll>>.
// But then the map might be large, but it's okay.
// So let me change to:
pair<ll,ll> h_s1 = hash_s1;
pair<ll,ll> h_s2 = hash_s2;
pair<pair<ll,ll>, pair<ll,ll>> key = make_pair(h_s1, h_s2);
length_map[len][key]++; // But wait, map doesn't support this key type? We can use map with key of type pair<pair<ll,ll>, pair<ll,ll>>.
// But then when we query, we will have the hashes for t1 and t2 as two pairs, so we can form the same key.
// However, note that for a given length len, the number of keys may be the number of distinct (s1,s2) pairs with that length.
// So let me use:
// map<int, map<pair<pair<ll,ll>, pair<ll,ll>>, int>> length_map;
// But then the key is a bit complex.
// Another idea: use a single hash for s1 and a single hash for s2? But then we might have collisions. So use double hashing for each string.
// So for the binary group, we have four hashes: for s1: (a1, a2), for s2: (b1, b2). Then we can combine them into one hash for the pair? Not necessary.
// When we query, for a given l and len, we will compute the hash of t1[l:l+len] as (a1, a2) and the hash of t2[l:l+len] as (b1, b2). Then we want to check if there is a binary group with length len that has s1 hash (a1,a2) and s2 hash (b1,b2).
// So if we store in length_map[len] a set of pairs of pairs: ( (a1,a2), (b1,b2) ) and then we can use a map that has key as ( (a1,a2), (b1,b2) ) and value count.
// How to represent the key? We can use a tuple of four ll: tuple<ll,ll,ll,ll> but then map requires less than operator. So we can use pair<pair<ll,ll>, pair<ll,ll>> which has less than operator.
// So let me use:
// map<int, map<pair<pair<ll,ll>, pair<ll,ll>>, int>> length_map;
// But then the code might be slow because of the map.
// Alternatively, we can use a single hash for the pair by hashing the four values into one value? But then we might have collisions.
// Since the total number of binary groups is 200000, we can use a set of four-tuples for each length.
// But then for each query, for each l and len, we need to check whether the four-tuple is in the set for len.
// So let me use:
// Precomputation:
map<int, set<tuple<ll,ll,ll,ll>>> length_set;
// But then we need to know the count? So use map from four-tuple to count.
// So use map<int, map<tuple<ll,ll,ll,ll>, int>> length_map; but tuple doesn't have default less than? wait, tuple has less than if the elements have less than.
// So we can use tuple<ll,ll,ll,ll> as key.
// Let me use:
map<int, map<tuple<ll,ll,ll,ll>, int>> length_map;
// For each binary group i:
ll a1 = hash_s1.first, a2 = hash_s1.second;
ll b1 = hash_s2.first, b2 = hash_s2.second;
tuple<ll,ll,ll,ll> key = make_tuple(a1, a2, b1, b2);
length_map[len][key]++;
}
// Then for each query:
for (int i=0; i<q; i++) {
string t1, t2;
cin >> t1 >> t2;
int L1 = t1.size(), L2 = t2.size();
if (L1 != L2) {
cout << 0 << '\n';
continue;
}
// Find A and B
int A = -1, B = -1;
vector<int> mismatches;
for (int i=0; i<L1; i++) {
if (t1[i] != t2[i]) {
mismatches.push_back(i);
}
}
if (mismatches.empty()) {
// but t1 != t2, so this should not happen, but if happen, then no substitution because t1=t2? but then why would we need to substitute? So output 0.
cout << 0 << '\n';
continue;
}
// Check if mismatches are continuous?
int continuous = true;
for (int i=1; i<mismatches.size(); i++) {
if (mismatches[i] != mismatches[i-1] + 1) {
continuous = false;
break;
}
}
if (!continuous) {
cout << 0 << '\n';
continue;
}
A = mismatches[0];
B = mismatches.back();
int min_len = B - A + 1;
// Precompute hashers for t1 and t2
Hasher H_t1(t1), H_t2(t2);
ll answer = 0;
// Get the lengths from length_map that are >= min_len
auto it = length_map.lower_bound(min_len);
for (; it != length_map.end(); it++) {
int len = it->first;
if (len > L1) break;
int low = max(0, B - len + 1);
int high = min(A, L1 - len);
if (low > high) continue;
auto & count_map = it->second;
for (int l = low; l <= high; l++) {
auto hash_t1 = H_t1.get_hash(l, l+len-1);
auto hash_t2 = H_t2.get_hash(l, l+len-1);
tuple<ll,ll,ll,ll> key = make_tuple(hash_t1.first, hash_t1.second, hash_t2.first, hash_t2.second);
if (count_map.find(key) != count_map.end()) {
answer += count_map[key];
}
}
}
cout << answer << '\n';
}
return 0;
}
But note: in the precomputation of hashers for the binary groups, we have to use the same hasher parameters as for the queries.
Also, we need to ensure that the hasher for the binary groups uses the same base and mod as the hasher for the queries.
So, we use the same Hasher class for both.
However, when hashing the binary group strings, we don't need to store the Hasher object, only the hash values.
So, in the precomputation, for each binary group, we compute the hash values using the Hasher class.
But note: the Hasher class for a string computes the prefix hashes. But for a small string, we can compute the hash without building the Hasher object? We can compute the hash by iterating.
Let me write a function to compute the hash of a string s without building Hasher:
pair<ll,ll> compute_hash(string &s) {
ll h1 = 0, h2 = 0;
for (char c : s) {
h1 = (h1 * base1 + c) % mod1;
h2 = (h2 * base2 + c) % mod2;
}
return {h1, h2};
}
This gives the hash for the entire string.
So, for the binary group, we can use this function to compute the hash of s1 and s2.
So, we don't need the Hasher class for the binary groups.
Similarly, for the queries, we need to compute the hash of substrings of t1 and t2, so we need the Hasher class that supports substrings.
So, let me use the compute_hash function for the binary groups, and use the Hasher class for the queries.
Now, the code for the precomputation becomes:
map<int, map<tuple<ll,ll,ll,ll>, int>> length_map;
for (int i=0; i<n; i++) {
string s1 = s1_list[i], s2 = s2_list[i];
int len = s1.size();
auto h1 = compute_hash(s1);
auto h2 = compute_hash(s2);
tuple<ll,ll,ll,ll> key = make_tuple(h1.first, h1.second, h2.first, h2.second);
length_map[len][key]++;
}
And for the queries, we use Hasher for t1 and t2.
Now, let me test with the sample.
Sample:
4 2
xabcx xadex
ab cd
bc de
aa bb
xabcx xadex
aaaa bbbb
For the first query: t1="xabcx", t2="xadex", L1=5.
Find mismatches:
t1: x a b c x
t2: x a d e x
So mismatches at indices 2 and 3? So A=2, B=3, min_len=2.
Then we consider lengths >=2.
What are the binary groups?
("xabcx", "xadex") len=5
("ab", "cd") len=2
("bc", "de") len=2
("aa", "bb") len=2
So for len=5: low = max(0, B-len+1) = max(0,3-5+1)= max(0,-1)=0
high = min(A, L1-len) = min(2,5-5)=0
So l=0.
Check at l=0:
hash_t1 = hash of t1[0:5] = "xabcx"
hash_t2 = hash of t2[0:5] = "xadex"
Compare with binary group 1: hashes match? yes.
So add 1.
For len=2:
low = max(0,3-2+1)= max(0,2)=2
high = min(2,5-2)=2
So l=2.
Check at l=2:
t1[2:4] = "bc"
t2[2:4] = "de"
Check with binary groups:
group2: ("ab","cd") -> not match because s1="ab" but we have "bc", so no.
group3: ("bc","de") -> match because s1="bc" and s2="de", so yes.
group4: ("aa","bb") -> no.
So add 1 for group3.
So total answer=2.
So it works.
For the second query: t1="aaaa", t2="bbbb", L1=4.
Mismatches: all indices? So A=0, B=3, min_len=4.
Then we consider len>=4.
What binary groups have len=4? None from the input? So answer=0.
So it works.
Now, we need to consider performance.
In the worst case, if there are many lengths, and for each length, the range [ low, high ] is large, then might be slow. But from earlier analysis, it should be acceptable.
Let me code accordingly.
Note: the compute_hash function must use the same base and mod as the Hasher class.
So, we define:
const int base1 = 131, base2 = 13131;
const int mod1 = 1e9+7, mod2 = 1e9+9;
pair<ll,ll> compute_hash(string &s) {
ll h1 = 0, h2 = 0;
for (char c : s) {
h1 = (h1 * base1 + c) % mod1;
h2 = (h2 * base2 + c) % mod2;
}
return {h1, h2};
}
And the Hasher class as above.
We'll implement this.
One more thing: the map length_map might be large, but the number of distinct lengths is at most the number of binary groups, which is 200000, but actually the number of distinct lengths might be less.
Also, for each length, the map of keys might be large, but the total number of keys is n=200000.
So, we proceed.
Code:
Note: we need to include <tuple> for tuple? But we use tuple in map, so it should be available.
Actually, we can use pair<pair<ll,ll>, pair<ll,ll>> instead of tuple for better performance? Or use tuple.
Let me use tuple since it's straightforward.
But when using tuple, we need to use make_tuple and then compare.
Now, let's code.
We'll use:
map<int, map<tuple<ll,ll,ll,ll>, int>> length_map;
Then when iterating over lengths, we use:
for (auto & [len, count_map] : length_map) {
if (len < min_len) continue;
if (len > L1) break;
...
}
But note: the map of lengths is sorted by key, so we can use lower_bound to start from min_len.
So:
auto it = length_map.lower_bound(min_len);
while (it != length_map.end() && it->first <= L1) {
int len = it->first;
...
it++;
}
But note: L1 might be small, so we break if len > L1.
Now, we code.
We need to be cautious about the range of l: l from low to high.
We hope this passes.
Let me test with the sample provided in the problem.
We'll run the code on the sample inputs.
One potential issue: the hasher might have collisions, but with double hashing, it should be safe.
Another issue: the total work might be high for some queries, but since the total L2 is 5e6, the number of queries with large L1 might be few.
So, we output the code.
Note: we need to use long long for the hashes.
Code implementation:
::::
::::info[最终思路]
为了解决这个问题,我们需要找到所有可能的替换方式,使得通过一次替换操作将字符串 $t_1$ 转换为 $t_2$。替换操作要求替换一个子串 $y$ 为 $y'$,其中 y 必须等于某个给定的二元组中的 $s_{i,1}$,$y'$ 必须等于对应的 $s_{i,2}$,并且替换后的整个字符串必须等于 $t_2$。
预处理二元组:将所有二元组按字符串长度分组,并存储每个长度下所有 $(s_{i,1}, s_{i_2})$ 对的哈希值及其出现次数。
查询处理:对于每个查询,检查 $t1$ 和 $t2$ 的长度是否相等。如果不相等,直接返回0。
查找不匹配区间:找到 $t1$ 和 $t2$ 中所有不匹配的位置。如果这些位置不连续,则返回0,因为一次替换只能改变一个连续区间。
计算候选区间:确定替换必须覆盖的最小长度 ```min_len```,即不匹配区间的长度。
检查有效替换:对于每个长度不小于 ```min_len``` 的二元组,检查是否存在起始位置 $l$,使得 $t_1$ 的子串 $[l, l+len-1]$ 等于 $s_{i,1}$,且 $t_2$ 的对应子串等于 $s_{i,2}$。同时确保替换区间外的部分匹配。
统计结果:统计所有有效的替换方式,包括不同的起始位置和二元组。
::::
::::info[code]
include <bits/stdc++.h>
using namespace std; typedef long long ll;
const int base1 = 131; const int base2 = 13131; const int mod1 = 1e9+7; const int mod2 = 1e9+9;
pair<ll, ll> compute_hash(const string &s) { ll h1 = 0, h2 = 0; for (char c : s) { h1 = (h1 base1 + c) % mod1; h2 = (h2 base2 + c) % mod2; } return {h1, h2}; }
class Hasher { public: vector<ll> H1, H2; vector<ll> pow1, pow2; string s; int n; Hasher(const string &str) { s = str; n = s.size(); H1.resize(n+1); H2.resize(n+1); pow1.resize(n+1); pow2.resize(n+1); pow1[0] = 1; pow2[0] = 1; for (int i = 1; i <= n; i++) { pow1[i] = (pow1[i-1] base1) % mod1; pow2[i] = (pow2[i-1] base2) % mod2; } for (int i = 0; i < n; i++) { H1[i+1] = (H1[i] base1 + s[i]) % mod1; H2[i+1] = (H2[i] base2 + s[i]) % mod2; } } pair<ll, ll> get_hash(int l, int r) { ll hash1 = (H1[r+1] - H1[l] pow1[r-l+1] % mod1 + mod1) % mod1; ll hash2 = (H2[r+1] - H2[l] pow2[r-l+1] % mod2 + mod2) % mod2; return {hash1, hash2}; } };
int main() { ios::sync_with_stdio(false); cin.tie(0);
int n, q;
cin >> n >> q;
map<int, map<tuple<ll, ll, ll, ll>, int>> length_map;
for (int i = 0; i < n; i++) {
string s1, s2;
cin >> s1 >> s2;
int len = s1.size();
auto h1 = compute_hash(s1);
auto h2 = compute_hash(s2);
auto key = make_tuple(h1.first, h1.second, h2.first, h2.second);
length_map[len][key]++;
}
while (q--) {
string t1, t2;
cin >> t1 >> t2;
int L1 = t1.size(), L2 = t2.size();
if (L1 != L2) {
cout << 0 << '\n';
continue;
}
vector<int> mismatches;
for (int i = 0; i < L1; i++) {
if (t1[i] != t2[i]) {
mismatches.push_back(i);
}
}
if (mismatches.empty()) {
cout << 0 << '\n';
continue;
}
bool continuous = true;
for (int i = 1; i < mismatches.size(); i++) {
if (mismatches[i] != mismatches[i-1] + 1) {
continuous = false;
break;
}
}
if (!continuous) {
cout << 0 << '\n';
continue;
}
int A = mismatches[0];
int B = mismatches.back();
int min_len = B - A + 1;
Hasher H_t1(t1), H_t2(t2);
ll answer = 0;
auto it = length_map.lower_bound(min_len);
while (it != length_map.end() && it->first <= L1) {
int len = it->first;
int low = max(0, B - len + 1);
int high = min(A, L1 - len);
if (low <= high) {
auto &count_map = it->second;
for (int l = low; l <= high; l++) {
auto hash_t1 = H_t1.get_hash(l, l + len - 1);
auto hash_t2 = H_t2.get_hash(l, l + len - 1);
auto key = make_tuple(hash_t1.first, hash_t1.second, hash_t2.first, hash_t2.second);
if (count_map.find(key) != count_map.end()) {
answer += count_map[key];
}
}
}
it++;
}
cout << answer << '\n';
}
return 0;
}
::::
[record:40pts](https://www.luogu.com.cn/record/245852403)
## T4