[Leaf] [CF2164D] Copy String

cf2164d---copy-string">CF2164D - Copy String

1. 核心逻辑

  • 模型抽象:

    • 给定变换规则 si′∈{si,si−1}s'_i \in \{s_i, s_{i-1}\},本质上是字符在单次操作中最多向右移动 1 位。
  • 破局路径:

    1. 位移转化: 目标字符串 tt 的位置 jj 需要字符 bjb_j,该字符必须由 ss 中的某个位置 ii 贡献。满足 si=bjs_i = b_j 且 i≤ji \le j。

    2. 贪心匹配: 为使总步数最小,对于每个 jj,应选择满足条件的最大索引 ii。这可以通过从右向左的一次线性扫描完成。

    3. 不变量判定: 单次操作最大位移为 1,故位置 jj 就位所需的步数为 j−ij - i。全局最小步数即为所有位置位移的最大值 K=max⁡{j−i}K = \max \{j - i\}。

    4. 构造仿真: 在第 stepstep 步时,位置 jj 的字符取决于其目标来源索引与当前传播距离的权衡,即 idx=max⁡(j−offset[j],j−step)idx = \max(j - offset[j], j - step)。

  • 细节处理:

    • 使用 a = ' ' + a 进行 1-indexed 偏移对齐。

    • 若某个字符无法在左侧找到匹配项,则输出 -1。

    • 若 max⁡{offset}>kmax\max \{offset\} > k_{max},输出 -1。

2. 代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
#include <bits/stdc++.h>
using namespace std;
using ll = long long;

const int maxn = 1e6 + 5;

int offset[maxn];
int n, k;
string a, b;

void solve( )
{
cin >> n >> k;
for( int i = 1; i <= n; ++ i )
{
offset[i] = -1;
}

cin >> a >> b;
a = ' ' + a;
b = ' ' + b;

bool ok = 1;
int res = 0;
int i = n;

for( int j = n; j >= 1 && i >= 1; -- j )
{
i = min( i, j );

while( i >= 1 && a[i] != b[j] ) i --;
if( a[i] == b[j] ) offset[j] = j - i;

res = max( res, offset[j] );
if( offset[j] == -1 ) ok = 0;
}

if( res > k || ok == 0 )
{
cout << -1 << '\n';
}
else
{
cout << res << '\n';
string row = string( n, ' ' );
for( int step = 1; step <= res; ++ step )
{
for( int j = 1; j <= n; ++ j )
{
int idx = max( j - offset[j], j - step );
row[j-1] = a[idx];
}
cout << row << '\n';
}
}
}

int main( )
{
ios::sync_with_stdio(0);
cin.tie(0); cout.tie(0);

int _t = 1;
cin >> _t;
while( _t -- )
{
solve( );
}
return 0;
}

3. 复盘

  • 复杂度: O(N⋅K)O(N \cdot K) 用于输出,逻辑匹配为 O(N)O(N)。

  • 灵感反思: 该变换规则初看具有递归性(si′s'_i 依赖于 si−1s_{i-1}),但拆解后发现其本质是扩散。通过维护 offset 数组,将动态的传播过程静态化为“距离”计算,是典型的构造降维思路。

  • 关联母题: 构造策略


[Leaf] [CF2164D] Copy String
http://miqiu.space/posts/ed8782a8/
作者
Miqiu
发布于
2026年1月6日
许可协议