Cod sursa(job #3040582)

Utilizator AleXutzZuDavid Alex Robert AleXutzZu Data 30 martie 2023 09:53:11
Problema Trie Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.98 kb
#include <iostream>
#include <fstream>

struct {
    int words = 0;
    int in_words = 0;
} graph[100][26][26];

void dfs(const std::string &str, bool subtract = false, int row = 0, int ptr = 0) {
    if (ptr == str.size() - 1) {
        if (ptr == 0) {
            if (!subtract) graph[row][0][str[ptr] - 'a'].words++;
            else graph[row][0][str[ptr] - 'a'].words--;

            if (!subtract) graph[row][0][str[ptr] - 'a'].in_words++;
            else graph[row][0][str[ptr] - 'a'].in_words--;
            return;
        }

        if (!subtract) graph[row][str[ptr - 1] - 'a'][str[ptr] - 'a'].words++;
        else graph[row][str[ptr - 1] - 'a'][str[ptr] - 'a'].words--;

        if (!subtract) graph[row][str[ptr - 1] - 'a'][str[ptr] - 'a'].in_words++;
        else graph[row][str[ptr - 1] - 'a'][str[ptr] - 'a'].in_words--;

        return;
    }

    if (ptr == 0) {
        if (!subtract) graph[row][0][str[ptr] - 'a'].in_words++;
        else graph[row][0][str[ptr] - 'a'].in_words--;
    } else {
        if (!subtract) graph[row][str[ptr - 1] - 'a'][str[ptr] - 'a'].in_words++;
        else graph[row][str[ptr - 1] - 'a'][str[ptr] - 'a'].in_words--;
    }

    dfs(str, subtract, row + 1, ptr + 1);
}

int count(const std::string &str, int row = 0, int ptr = 0) {
    if (ptr == str.size() - 1) return graph[row][str[ptr - 1] - 'a'][str[ptr] - 'a'].words;
    return count(str, row + 1, ptr + 1);
}

int find_max(const std::string &str, int row = 0, int ptr = 0) {
    if (str.size() - 1 == ptr) return 0;
    return std::max(graph[row][str[ptr - 1] - 'a'][str[ptr] - 'a'].in_words > 0 ? row + 1 : 0,
                    find_max(str, row + 1, ptr + 1));
}

int main() {
    std::ifstream input("trie.in");
    std::ofstream output("trie.out");

    int op;
    std::string str;

    while (input >> op >> str) {
        if (op == 0) dfs(str);
        else if (op == 1) dfs(str, true);
        else if (op == 2) output << count(str) << '\n';
        else output << find_max(str) << '\n';
    }

    return 0;
}