Cho cây với trọng số là chuỗi. Đếm nút có chuỗi chứa ít nhất một nguyên âm (a, e, i, o, u).
Ý tưởng
- DFS trên cây (biểu diễn bằng
edge_graphvàNode_Weightkiểu string). - Hàm
check(str)duyệt chuỗi, chuyển về chữ thường, kiểm tra ký tự nguyên âm. - Hàm
string_vowel(node, root)đệ quy đếm.
Ví dụ hoàn chỉnh
#include <bits/stdc++.h>
using namespace std;
vector<string> Node_Weight(100);
vector<int> edge_graph[100];
int vowel = 0;
bool check(string check_it) {
int length = check_it.length();
for (int i = 0; i < length; i++) {
char c = tolower(check_it[i]);
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u')
return true;
}
return false;
}
void string_vowel(int node, int root) {
string str = Node_Weight[node];
if (check(str))
vowel++;
for (int it : edge_graph[node]) {
if (it == root)
continue;
string_vowel(it, node);
}
}
int main() {
Node_Weight[2] = "ae";
Node_Weight[1] = "bcd";
Node_Weight[4] = "io";
Node_Weight[3] = "gfe";
Node_Weight[8] = "tptpa";
Node_Weight[9] = "iou";
edge_graph[2].push_back(1);
edge_graph[2].push_back(4);
edge_graph[4].push_back(3);
edge_graph[4].push_back(8);
edge_graph[8].push_back(9);
string_vowel(2, 2);
cout << "Số nút có chuỗi chứa nguyên âm: " << vowel;
return 0;
}
Kết quả
Số nút có chuỗi chứa nguyên âm: 5