P14405 [JOISC 2015] 复制粘贴 2 / Copy and Paste 2
思路
题意足够清晰这里不再赘述。
由于 达到 ,跑暴力是不可能的,但我们可以观察到 ,所以我们只需追踪这 个字符的来源,不用去管整个字符串。所以我们对于最终字符串的每个位置 ,可以直接逆序遍历,追踪它在初始字符串 中的原始位置就行。
预处理
为第 次操作后字符串的长度,对于第 次操作:
- 复制的子串长度为 。
- 操作后理论长度为 。
- 实际长度为 。
逆序追踪
以最终字符串的位置 为例,逆序遍历操作 :
- 设第 j 次操作前长度为 ,操作后长度为 。
- 复制长度 ,插入位置 。
- 分三种情况处理 :
- 若 :位置在插入区域左侧,不受影响
- 若 :该字符来自复制的子串,映射为 。
- 若 :位置在插入区域右侧,需向左偏移 。
正向补充追踪
正向就很简单了,如果逆向追踪后, 仍大于初始字符串长度,说明该字符来自中间操作生成的内容,需要正向遍历操作继续查找:
- 遍历操作 ,重复类似的映射逻辑
- 最多追踪 次,直到 落在初始字符串范围内即可。
时间复杂度为 。
空间复杂度为 。
Code
#include<bits/stdc++.h>
using namespace std;
#define int long long
constexpr int N = 78787878;
int k, m, n, cnt, len[N];
string s, ss;
array<int, 3> a[N];
namespace fastIO{
char *p1,*p2,buf[100000];
#define nc() (p1==p2&&(p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++)
inline void read(int&n){int x=0,f=1;char ch=nc();while(ch<48||ch>57){if(ch=='-'){f=-1;}ch=nc();}while(ch>=48&&ch<=57){x=(x<<3)+(x<<1)+(ch^48),ch=nc();}n=x*f;}
inline void read(string&s){char ch=nc();while(ch==' '||ch=='\n'){ch=nc();}while(ch!=' '&&ch!='\n'){s+=ch,ch=nc();}}
inline void write(const string&s){for(register int i=0;i<(int)s.size();i++){putchar(s[i]);}}
}
using namespace fastIO;
signed main(){
read(k); read(m); read(s); read(n);
for(int i = 0; i < n; i++){
read(a[i][0]); read(a[i][1]); read(a[i][2]);
}
len[0] = s.size();
for(int i = 0; i < n; i++){
int temp1 = len[i]; // 操作前长度
int temp2 = a[i][1] - a[i][0]; // 复制的长度
int temp3 = temp1 + temp2; // 操作后长度(未截断)
if (temp3 > m) temp3 = m; // 截断到最大长度m
len[i + 1] = temp3;
}
int sum = len[n]; // 最终字符串长度
for(int i = 0; i < k; i++){ // 处理前k个字符
if(i >= sum) break; // 如果超出最终长度,无需处理
int temp = i; // 当前追踪的位置
cnt = 0; // 计数器,防止无限循环
// 逆向追踪所有操作
for(int j = n - 1; j >= 0; j--){
auto& op = a[j];
int A = op[0], B = op[1], C = op[2];
int temp1 = len[j]; // 操作j前的长度
int temp2 = len[j + 1]; // 操作j后的长度
int temp3 = B - A; // 复制的长度
if(temp >= temp2) continue; // 位置超出当前操作后的长度,不处理
if(temp < C){
// 位置在粘贴区域前,不变
}else if(temp < C + temp3){
// 位置在粘贴区域内,映射到复制源
temp = A + (temp - C);
}else{
// 位置在粘贴区域后,调整位置
temp -= temp3;
}
}
// 如果仍未找到初始字符串中的位置,继续正向查找
int maxx = n;
while(temp >= s.size() && cnt < maxx){
bool f = false;
for(int j = 0; j < n; j++){
auto& op = a[j];
int A = op[0], B = op[1], C = op[2];
int temp1 = len[j];
int temp2 = len[j + 1];
int temp3 = B - A;
if(temp >= temp2) continue;
if(temp < C){
continue;
}else if(temp < C + temp3){
temp = A + (temp - C);
f = true;
break;
}else{
temp -= temp3;
f = true;
break;
}
}
if(!f){
temp = -1;
break;
}
cnt++;
}
// 如果找到有效位置,添加到结果
if(temp >= 0 && temp < s.size()){
ss += s[temp];
}
}
write(ss);
return 0;
}