ZOJ 3674 Search in the Wiki(字典樹 + map + vector)
阿新 • • 發佈:2018-12-24
題意:每個單詞都一些tips單詞。先輸入n個單詞和他們的tips。然後m組查詢,每次查詢一些單詞,按字典序輸出這些單詞的公有tips。(每個單詞都都只包含小寫大寫字母)
思路:對第i個單詞,用vector陣列g,g[i]來存這個單詞的所有tips。對於所有單詞建立字典樹,在單詞的結尾結點存好該單詞的tips在g陣列中存的一維下標i。最後用map來計數每組詢問中每個tips。每組詢問中,對於所有的查詢單詞中所有的tips計數值等於單詞個數的進行記錄,最終按字典序排序,最後輸出。
程式碼:
#include <iostream> #include <stdio.h> #include <string.h> #include <string> #include <map> #include <set> #include <algorithm> #include <vector> using namespace std; const int N = 3e3 + 10; const int SIZE = 60; const int MAX_WORD = 305; struct Trie { int val[SIZE]; int w; }; int sz; char str[MAX_WORD]; char st[MAX_WORD]; Trie pn[N]; map<string, int> m; vector<string> g[N]; vector<string> res; int newnode() { memset(pn[sz].val, 0, sizeof(pn[sz].val)); pn[sz].w = -1; return sz++; } void init() { sz = 0; newnode(); } void insert(char *s, int j) { int u = 0; int len = strlen(s); for (int i = 0; i < len; i++) { int idx = s[i] - 'A'; if (!pn[u].val[idx]) pn[u].val[idx] = newnode(); u = pn[u].val[idx]; } pn[u].w = j; string t; gets(str); len = strlen(str); for (int i = 0; i < len; i++) { if (str[i] == ' ') { g[j].push_back(t); t.clear(); } else t.push_back(str[i]); } if (!t.empty()) g[j].push_back(t); } int findstr(char *s) { int u = 0; int len = strlen(s); for (int i = 0; i < len; i++) { int idx = s[i] - 'A'; if (!pn[u].val[idx]) return -1; u = pn[u].val[idx]; } if (g[pn[u].w].empty()) return -1; for (int i = 0; i < g[pn[u].w].size(); i++) m[g[pn[u].w][i]]++; return u; } int main() { int n, q; while (scanf("%d", &n) != EOF) { init(); for (int i = 0; i < n; i++) { scanf("%s", str); getchar(); g[i].clear(); insert(str, i); } scanf("%d", &q); getchar(); int k, t; for (int i_q = 1; i_q <= q; i_q++) { m.clear(); gets(str); int y = 0; t = 0; int len = strlen(str); for (int i = 0; i < len; i++) { st[y++] = str[i]; if (str[i + 1] == '\0' || str[i + 1] == ' ') { st[y] = '\0'; k = findstr(st); if (k == -1) break; t++; y = 0; i++; } } if (k == -1) { puts("NO"); continue; } res.clear(); for (int i = 0; i < g[pn[k].w].size(); i++) if (m[g[pn[k].w][i]] == t) res.push_back(g[pn[k].w][i]); if (res.empty()) puts("NO"); else { sort(res.begin(), res.end()); for (int i = 0; i < res.size() - 1; i++) cout << res[i] << " "; cout << res[res.size() - 1] << endl; } } } return 0; }