题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=4917
题意:每个单词都一些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;
}