Acwing-----算法基础课之第二讲

831. KMP字符串

#include <iostream>

using namespace std;
const int N = 10010, M = 100010;

int n, m;
char s[M], p[N];
int ne[N];

int main() {
    cin >> n >> p + 1 >> m >> s + 1;
    for (int i = 2, j = 0; i <= n; ++i) {
        while (j && p[i] != p[j + 1]) j = ne[j];
        if (p[i] == p[j + 1]) ++j;
        ne[i] = j;
    }
    
    for (int i = 1, j = 0; i <= m; ++i) {
        while (j && s[i] != p[j + 1]) j = ne[j];
        if (s[i] == p[j + 1]) ++j;
        if (j == n) {
            cout << i - n << " ";
            j = ne[j];
        }
    }
    return 0;
}

835. Trie字符串统计

#include <iostream>
using namespace std;

const int N = 100010;

int son[N][26], cnt[N], idx, n;
char str[N];

void insert(char* str) {
    int p = 0;
    for (int i = 0; str[i]; ++i) {
        int u = str[i] - 'a';
        if (!son[p][u]) son[p][u] = ++idx;
        p = son[p][u];
    }
    cnt[p]++;
}

int query(char* str) {
    int p = 0;
    for (int i = 0; str[i]; ++i) {
        int u = str[i] - 'a';
        if (!son[p][u]) return 0;
        p = son[p][u];
    }
    return cnt[p];
}


int main() {
    cin >> n;
    while (n--) {
        char op[2];
        scanf("%s%s", &op, &str);
        if (*op == 'I') insert(str);
        else cout << query(str) << endl;
    }
    return 0;
}

836. 合并集合

#include <iostream>
using namespace std;

const int N = 100010;
int n, m;
int p[N];

int find(int x) {
    if (p[x] != x) p[x] = find(p[x]);
    return p[x];
}

int main() {
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; ++i) p[i] = i;
    
    while (m--) {
        char op[2];
        int a, b;
        scanf("%s%d%d", op, &a, &b);
        
        if (op[0] == 'M') p[find(a)] = find(b);
        else {
            if (find(a) == find(b)) puts("Yes");
            else puts("No");
        }
    }
    return 0;
}

838. 堆排序

#include <iostream>
#include <algorithm>

using namespace std;

const int N = 100010;

int n, m;
int h[N], sz;

void down(int u) {
    int t = u;
    if (u * 2 <= sz && h[u * 2] < h[t]) t = u * 2;
    if (u * 2 + 1 <= sz && h[u * 2 + 1] < h[t]) t = u * 2 + 1;
    if (u != t) {
        swap(h[u], h[t]);
        down(t);
    }
}

int main() {
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= n; ++i) scanf("%d", &h[i]);
    sz = n;
    
    for (int i = n / 2; i ; --i) down(i);
    while (m--) {
        printf("%d ", h[1]);
        h[1] = h[sz];
        sz--;
        down(1);
    }
    
    return 0;
}
原文地址:https://www.cnblogs.com/clown9804/p/12637913.html