添加 T642397.cpp 文件,实现算法逻辑并优化输入输出性能

This commit is contained in:
Zengtudor 2025-07-29 15:35:00 +08:00
parent a327277ca5
commit 75784f43da
2 changed files with 100 additions and 0 deletions

3
src/7/28/P11233.cpp Normal file
View File

@ -0,0 +1,3 @@
int main(){
}

97
src/7/29/T642397.cpp Normal file
View File

@ -0,0 +1,97 @@
#include <iostream>
#include <queue>
#include <cstring>
using namespace std;
const int N = 5005;
int dp[N][N];
string s, t;
int n, m;
queue<pair<int, int>> q;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
getline(cin, s);
getline(cin, t);
n = s.size();
m = t.size();
if (s == t) {
cout << 0 << '\n';
return 0;
}
bool found = false;
for (int i = 0; i <= n - m; i++) {
if (s.substr(i, m) == t) {
found = true;
break;
}
}
if (!found) {
cout << -1 << '\n';
return 0;
}
memset(dp, -1, sizeof(dp));
for (int i = 0; i < n; i++) {
for (int j = i; j < n; j++) {
if (j - i + 1 < m) continue;
if (s.substr(i, m) == t) {
dp[i][i + m - 1] = 0;
q.push({i, i + m - 1});
}
}
}
while (!q.empty()) {
auto [l, r] = q.front(); q.pop();
if (l == 0 && r == n - 1) {
cout << dp[l][r] << '\n';
return 0;
}
if (l > 0) {
for (int a = l - 1; a >= 0; a--) {
int len = l - a;
bool cannot = false;
for (int i = l; i <= r - len + 1; i++) {
if (s.substr(i, len) == s.substr(a, len)) {
cannot = true;
break;
}
}
if (cannot) {
if (dp[a][r] == -1) {
dp[a][r] = dp[l][r] + 1;
q.push({a, r});
}
}
}
}
if (r < n - 1) {
for (int b = r + 1; b < n; b++) {
int len = b - r;
bool cannot = false;
for (int i = l; i <= r - len + 1; i++) {
if (s.substr(i, len) == s.substr(r + 1, len)) {
cannot = true;
break;
}
}
if (cannot) {
if (dp[l][b] == -1) {
dp[l][b] = dp[l][r] + 1;
q.push({l, b});
}
}
}
}
}
cout << -1 << '\n';
return 0;
}