AcWing第126场周赛 - 思维+字符串处理+递归

AcWing 5280. 替换字符

直接暴力,但是需要注意初始化

#include 
using namespace std;
#define ll long long
#define sf(x) scanf("%d", &x);
#define de(x) cout << x << " ";
#define Pu puts("");
const int N = 1e5 + 9, mod = 1e9 + 7;
char a[N], b[N];
int n, m, ans;
int u[N], k;
void fun(int x) {
    int res = 0;
    for (int i = x; i <= x + n - 1; i++) {
        if (a[i - x + 1] == b[i])
            res++;
    }
    if ((n - res) < ans) {  // 如果当前子序列,需要需改的数量小于ans,则进行修改
        k = 0;
        for (int i = x; i <= x + n - 1; i++) {
            if (a[i - x + 1] != b[i]) {
                k++;
                u[k] = i - x + 1;
            }
        }
        ans = k;
    }
}
void init() {  // ans初始化
    ans = 0;
    for (int i = 1; i <= n; i++) {
        if (a[i] != b[i]) {
            ans++;
        }
    }
    k = 0;
    for (int i = 1; i <= n; i++) {
        if (a[i] != b[i]) {
            u[++k] = i;
        }
    }
}
int main() {
    cin >> n >> m;
    cin >> (a + 1);
    cin >> (b + 1);
    init();
    for (int i = 2; i <= m - n + 1; i++) {
        fun(i);
    }
    cout << ans << endl;
    for (int i = 1; i <= k; i++) {
        cout << u[i] << " ";
    }
    return 0;
}

AcWing 5281. 扩展字符串

这个题目参考的题解,很好的一个递归题目
参考题解
分情况进行讨论

#include 
using namespace std;
#define ll long long
#define sf(x) scanf("%d", &x);
#define de(x) cout << x << " ";
#define Pu puts("");
const int N = 1e5 + 9, mod = 1e9 + 7;
char a[N], b[N];
int n, m, ans;
int u[N], k;
void fun(int x) {
    int res = 0;
    for (int i = x; i <= x + n - 1; i++) {
        if (a[i - x + 1] == b[i])
            res++;
    }
    if ((n - res) < ans) {  // 如果当前子序列,需要需改的数量小于ans,则进行修改
        k = 0;
        for (int i = x; i <= x + n - 1; i++) {
            if (a[i - x + 1] != b[i]) {
                k++;
                u[k] = i - x + 1;
            }
        }
        ans = k;
    }
}
void init() {  // ans初始化
    ans = 0;
    for (int i = 1; i <= n; i++) {
        if (a[i] != b[i]) {
            ans++;
        }
    }
    k = 0;
    for (int i = 1; i <= n; i++) {
        if (a[i] != b[i]) {
            u[++k] = i;
        }
    }
}
int main() {
    cin >> n >> m;
    cin >> (a + 1);
    cin >> (b + 1);
    init();
    for (int i = 2; i <= m - n + 1; i++) {
        fun(i);
    }
    cout << ans << endl;
    for (int i = 1; i <= k; i++) {
        cout << u[i] << " ";
    }
    return 0;
}

你可能感兴趣的:(Codeforces,刷题+算法,AcWing,算法,c++,数据结构)