</pre><pre name="code" class="cpp">#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
using namespace std;
const int M = 26;
int n;
#define maxn 1005
char S[maxn][21];
struct Node
{
int v;
Node *next[M];
}*root;
void Creat(char *s) //分配内存最好使用calloc 因为会进行初始化 而malloc不初始化 都是随机的数据垃圾
{
int len = strlen(s);
Node *p = root, *q;
for(int i=0; i<len; i++)
{
int id = s[i] - 'a';
if(p->next[id] == NULL)
{
q = (Node *)calloc(1, sizeof(Node));
q->v = 1;
p->next[id] = q;
p = q;
}
else
{
p = p->next[id];
p->v++;
}
}
//p->v = -1; //标志最后一个为-1
}
int Find(char *s) //查找函数可更具需要修改
{
int cnt = 0;
int len = strlen(s);
Node *p = root;
for(int i=0; i<len; i++)
{
int id = s[i] - 'a';
p = p->next[id];
if(p == NULL)
return 0; //不存在
//if(p->v == -1)
// return -1;//已有串是此串前缀
}
return 1;// 此串是某已有串的前缀
}
char S1[12];
int main()
{
n = 0;
root = (Node *)calloc(1, sizeof(Node)); // 根节点
while(gets(S1) && S1[0] != '\0')
Creat(S1);
while(~scanf("%s", S1))
{
printf("%d\n", Find(S1));
}
///while(gets(S) && S)
}
/*
4
abc
def
gh
rr
10
*/
hdu 水题
最新推荐文章于 2019-11-20 21:47:13 发布