编辑
2023-10-21
数据结构与算法
00
请注意,本文编写于 566 天前,最后修改于 566 天前,其中某些信息可能已经过时。

P1481

cpp
#include <iostream> #include <vector> #include <algorithm> using namespace std; struct TrieNode { TrieNode* children[26]; int depth; TrieNode() { for (int i = 0; i < 26; i++) { children[i] = nullptr; } depth = 0; } }; int findLongestWordChain(vector<string>& words) { sort(words.begin(), words.end()); TrieNode* root = new TrieNode(); int maxLength = 0; for (const string& word : words) { TrieNode* cur = root; int length = 0; for (char c : word) { int index = c - 'a'; if (cur->children[index] == nullptr) { cur->children[index] = new TrieNode(); } cur = cur->children[index]; length = max(length, cur->depth); } cur->depth = length + 1; maxLength = max(maxLength, cur->depth); } return maxLength; } int main() { int n; cin >> n; vector<string> words; for (int i = 0; i < n; i++) { string word; cin >> word; words.push_back(word); } int result = findLongestWordChain(words); cout << result << endl; return 0; }

解法二 dp

cpp
#include <iostream> #include <vector> #include <string> using namespace std; int findLongestWordChain(vector<string> words) { int n = words.size(); vector<int> dp(n, 1); for (int i = 1; i < n; i++) { for (int j = 0; j < i; j++) { if (words[i].find(words[j]) == 0) { dp[i] = max(dp[i], dp[j] + 1); } } } int maxChainLength = 0; for (int i = 0; i < n; i++) { maxChainLength = max(maxChainLength, dp[i]); } return maxChainLength; } int main() { int n; cin >> n; vector<string> words(n); for (int i = 0; i < n; i++) { cin >> words[i]; } sort(words.begin(), words.end()); // Sort the words lexicographically int result = findLongestWordChain(words); cout << result << endl; return 0; }

本文作者:yowayimono

本文链接:

版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!