#1260 : String Problem I
-
3 3 tourist petr rng toosimple rg ptr
Sample Output -
0 1 1
Description
We have a set of strings S which contains N distrinct strings.
We have also M queries, each query with a string w, asking how many strings in S can be got by adding exactly one character to the string w.
The character can be added anywhere including before the head and after the tail.
For example, for string "abc"
and we adding "x", we can get "xabc", "axbc", "abxc", "abcx".
Input
First line with two numbers N and M, denoting the number of strings in S and the number of queries.
The following N lines, with one string in S on each line.
The following M lines, with one query string on each line.
All strings contain only lowercase letters.
Data Limit:
N,M<=10000
The sum of length of strings in S <=100000
The sum of length of all query strings <=100000
Output
For each query, print one integer denoting the answer.
思路:就是一个trie,建树的过程中标记串的末尾。然后在图上跑DFS就好了。
模拟太弱了,一直TLE。不得不用trie写了。。。
AC代码:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <vector>
#include <string>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define MAXN (100000+10)
#define MAXM (500000)
#define Ri(a) scanf("%d", &a)
#define Rl(a) scanf("%lld", &a)
#define Rf(a) scanf("%lf", &a)
#define Rs(a) scanf("%s", a)
#define Pi(a) printf("%d\n", (a))
#define Pf(a) printf("%.2lf\n", (a))
#define Pl(a) printf("%lld\n", (a))
#define Ps(a) printf("%s\n", (a))
#define W(a) while(a--)
#define CLR(a, b) memset(a, (b), sizeof(a))
#define MOD 1000000007
#define LL long long
#define lson o<<1, l, mid
#define rson o<<1|1, mid+1, r
#define ll o<<1
#define rr o<<1|1
#define PI acos(-1.0)
using namespace std;
bool vis[10001];
struct Trie
{
int next[MAXN][30], L, root, id[MAXN];
int newnode()
{
for(int i = 0; i < 26; i++)
next[L][i] = -1;
id[L++] = -1;
return L-1;
}
void init()
{
L = 0;
root = newnode();
}
void Insert(char *s, int ID)
{
int u = root, v;
for(int i = 0; s[i]; i++)
{
int v = s[i] - 'a';
if(next[u][v] == -1)
next[u][v] = newnode();
u = next[u][v];
}
id[u] = ID;
}
int ans;
void DFS(int u, int use, int pos, char *s)
{
if(s[pos])
{
for(int i = 0; i < 26; i++)
{
if(next[u][i] == -1) continue;
if(s[pos] == 'a' + i)
DFS(next[u][i], use, pos+1, s);
else if(use == 0)
DFS(next[u][i], use+1, pos, s);
}
}
else
{
if(use == 1)
{
if(id[u] != -1)
{
if(!vis[id[u]])
{
vis[id[u]] = true;
ans++;
}
}
// else
// {
// for(int i = 0; i < 26; i++)
// {
// if(next[u][i] == -1) continue;
// return DFS(next[u][i], 1, pos, s);
// }
// }
}
else
{
for(int i = 0; i < 26; i++)
{
if(next[u][i] == -1) continue;
else DFS(next[u][i], 1, pos, s);
}
}
}
}
};
Trie tree;
char str[MAXN];
int main()
{
int N, M;
while(scanf("%d%d", &N, &M) != EOF)
{
tree.init();
for(int i = 0; i < N; i++)
{
Rs(str);
tree.Insert(str, i);
}
W(M)
{
Rs(str);
CLR(vis, false); tree.ans = 0;
tree.DFS(tree.root, 0, 0, str);
Pi(tree.ans);
}
}
return 0;
}