Problem Type: Trie Data Structure
#include<bits/stdc++.h>
using namespace std;
struct Node
{
map<char, Node*> a;
int flag;
Node()
{
flag = 0;
}
};
Node* root;
void insert_text(Node *x, string s)
{
for(int i = 0; i < s.size(); i++)
{
if(x->a.count(s[i]) == 0)
{
x->a[ s[i] ] = new Node;
}
x = x->a[ s[i] ];
}
x->flag++;
}
int search_text(Node* x, string s)
{
int len = s.length();
int i=0;
int flag_count =0;
while (i<len)
{
char c = s[i];
if(x->a.count(s[i]) != 0)
{
x = x->a[s[i]];
if(x->flag==1)
{
flag_count++;
}
else if(x->flag>1)
{
return 0;
}
}
i++;
}
if(flag_count>1)
{
return 0;
}
else
{
return 1;
}
}
int main()
{
int test;
scanf("%d",&test);
for(int i=0; i<test; i++)
{
int how_number,k=0;
string str[10003];
root = new Node;
scanf("%d",&how_number);
int j;
for(j=0; j<how_number; j++)
{
string number;
cin >> number;
insert_text(root,number);
str[j]=number;
}
int mm=0;
for(int k=0; k<j; k++)
{
int p = search_text(root,str[k]);
if(p==0)
{
mm=1;
break;
}
}
if(mm==0)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
}
#include<bits/stdc++.h>
using namespace std;
struct Node
{
map<char, Node*> a;
int flag;
Node()
{
flag = 0;
}
};
Node* root;
void insert_text(Node *x, string s)
{
for(int i = 0; i < s.size(); i++)
{
if(x->a.count(s[i]) == 0)
{
x->a[ s[i] ] = new Node;
}
x = x->a[ s[i] ];
}
x->flag++;
}
int search_text(Node* x, string s)
{
int len = s.length();
int i=0;
int flag_count =0;
while (i<len)
{
char c = s[i];
if(x->a.count(s[i]) != 0)
{
x = x->a[s[i]];
if(x->flag==1)
{
flag_count++;
}
else if(x->flag>1)
{
return 0;
}
}
i++;
}
if(flag_count>1)
{
return 0;
}
else
{
return 1;
}
}
int main()
{
int test;
scanf("%d",&test);
for(int i=0; i<test; i++)
{
int how_number,k=0;
string str[10003];
root = new Node;
scanf("%d",&how_number);
int j;
for(j=0; j<how_number; j++)
{
string number;
cin >> number;
insert_text(root,number);
str[j]=number;
}
int mm=0;
for(int k=0; k<j; k++)
{
int p = search_text(root,str[k]);
if(p==0)
{
mm=1;
break;
}
}
if(mm==0)
{
printf("YES\n");
}
else
{
printf("NO\n");
}
}
}
No comments:
Post a Comment