2 条题解

  • 0
    @ 2024-12-10 16:07:30

    二叉字典树标准链表存储方式:

    #include <bits/stdc++.h>
    using namespace std;
    struct TrieNode {
        // 为简化,这里用一个固定大小的数组来存放指向子节点的指针。
        // 因为题中说明是大写英文字母,因此范围为 'A'-'Z',共26个。
        TrieNode* children[26];  
        TrieNode() {
            for (int i = 0; i < 26; i++) {
                children[i] = nullptr;
            }
        }
    };
    int main() {
        ios::sync_with_stdio(false);
        cin.tie(NULL);
        // 构建 Trie 的根节点
        TrieNode* root = new TrieNode();
        // 节点计数器(包括根节点)
        int node_count = 1;
        string word;
        // 从标准输入不断读取单词,直到 EOF 结束
        while (true) {
            if(! (cin >> word)) break; // 读取失败说明到达EOF
            // 将单词插入 Trie
            TrieNode* cur = root;
            for (auto c : word) {
                int idx = c - 'A';
                if (cur->children[idx] == nullptr) {
                    // 若对应子节点不存在,则创建新节点
                    cur->children[idx] = new TrieNode();
                    node_count++;
                }
                // 向下走
                cur = cur->children[idx];
            }
        }
        // 输出最终的节点数
        cout << node_count << "\n";
        return 0;
    }
    
    
    
    • 0
      @ 2024-12-10 16:05:05

      方法1:

      #include <bits/stdc++.h>
      using namespace std;
      int main() {
          vector<string> vec;
          string str;
          while(cin >> str) vec.push_back(str);
          //单词排序
          sort(vec.begin(), vec.end());
          int sum = vec[0].size();
          for (int i = 1; i < vec.size(); i++) {
              int j = 0;
              //求前后两个单词相同部分的长度
              while (j < vec[i - 1].size() && vec[i][j] == vec[i - 1][j]) j++;
              sum += vec[i].size() - j;  //累加两个单词的差
          }
          cout << sum + 1 << endl;
          return 0;
      }
      
      • 1

      信息

      ID
      815
      时间
      1000ms
      内存
      256MiB
      难度
      8
      标签
      递交数
      18
      已通过
      7
      上传者