#include <bits/stdc++.h> using namespace std;
// 初始化 S1 变量 startPos 和 endPos,分别用于存储有效子串 // 的起始和终止位置。 int startPos = -1, endPos = -1;
bool isValid(int len, string& S1, string& S2, int C, int target) { int i = 0, j = 0, n = S1.size(), cost = 0;
// 将 S1 变量标志初始化为 false。 //它会跟踪任何长度为 len 的有效子串是否可能。 bool flag = false;
while (j < n) {
// 包括将 S1[j] 转换为 S2[j] 所需的费用 cost += ((S1[j] != S2[j]) ? C : 0);
//如果窗口大小等于 len,则移动窗口。 if (j - i + 1 == len) {
// 检查是否存在有效子串,然后将有效子串的索引保留在 startPos 和 endPos 中 if (cost <= target) { flag = true; startPos = i; endPos = j; }
//移除计算 //用指数作为我们的窗口 //我们必须滑动我们的窗口 cost -= ((S1[j] != S2[j]) ? C : 0); i++; }
j++; }
// Return the flag return flag; }
void validSubstring(string S1, string S2, int C, int target) { startPos = -1, endPos = -1;
// 初始化 S1 变量以 // 最小有效长度 // 可能的子串。 int start = 0;
// 初始化 S1 变量,以 //可能的最大有效长度子串 //结束。 int end = S1.size(); int n = S1.size();
// 初始化 S1 变量结果,用于 // 存储 // 有效子串的最大长度。 int result = 0;
// 在起点小于终点时执行 // 小于等于终点时执行。 while (start < end) {
// Calculate the mid int mid = (start + end) / 2;
// 检查 mid 是否为可能的长度 // 为有效子串 if (isValid(mid, S1, S2, C, target)) {
// Assign result to mid result = mid;
// Shift start to mid + 1 start = mid + 1; }
// Otherwise shift end to mid - 1 else { end = mid; } }
if (startPos == -1) cout << "Not possible\n"; else cout << startPos << " " << endPos << "\n"; }
// Driver code int main() { // First test case string S1 = "abcd", S2 = "bcdf"; int C = 1, target = 5; validSubstring(S1, S2, C, target); // Second test case S1 = "abc", S2 = "cdf"; C = 10, target = 3; validSubstring(S1, S2, C, target);
// Third test case S1 = "abcb", S2 = "cdfb"; C = 2, target = 2; validSubstring(S1, S2, C, target);
return 0; }
|