12506

#include <iostream>
#include <string>
#include <queue>

using namespace std;
int res;
struct node{
	int cont;
	node *next[26];

	node()
	{
		cont=0;

		for(int i=0;i<26;i++)
		next[i]=NULL;
	}

}*root;

void insert(string s)
{
	node *tmp= root;
	int len=s.size();
	int idx;
	for(int i=0;i<len;i++)
	{
		idx= s[i]-'a';
		if(tmp->next[idx]==NULL)
			tmp->next[idx]=new node();

		tmp->next[idx]->cont++;
		tmp = tmp->next[idx];
	}
}

void del(node *r)
{
	for(int i=0;i<26;i++)
		if(r->next[i]!=NULL)
		  del(r->next[i]);

	delete(r);
}

int solve()
{
	queue<node*> q;
	node *tmp= new node();

	res=0;
	q.push(root);

	while(!q.empty())
	{
		tmp = q.front();
		q.pop();

		for(int i=0;i<26;i++)
		{
			if(tmp->next[i]!=NULL)
			{
				res+=tmp->next[i]->cont;
				if((tmp->next[i]->cont)>1)
       			q.push(tmp->next[i]);
			}

		}
	}
}
int main()
{
	int t,n;
	string str;

	cin>>t;
	while(t--)
	{
		cin>>n;
		root = new node();
		for(int i=0;i<n;i++)
		{
			cin>>str;
			insert(str);
			//cout<<"inserted\n";
		}

		solve();
		cout<<res<<"\n";
		del(root);
	}

	return 0;
}

 

Leave a Reply

Your email address will not be published. Required fields are marked *