hdu1671 Phone List

簡單題~

注意del();

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
#include <algorithm>
#include <vector>
#include <limits.h>
#include <queue>
#include <stack>
using namespace std;
struct trie
{
    int is;
    trie* next[11];
};

char ch[11];
int ans;
void inst(trie *root,char* s)
{
    trie *p = root;
    int i = 0,len = strlen(s),f = 1,ff=1;
    //cout<<s<<endl;
    while(i < len)
    {
        //cout<<i<<endl;
        int k = s[i]-'0';
        if(p->next[k] == NULL)
        {
            //cout<<i<<endl;
            trie* tmp = new trie;
            //cout<<i<<endl;
            for(int j= 0;j < 11;j ++) tmp->next[j] = NULL;
            tmp->is = 0;
            p->next[k] = tmp;
        }
        else
        {
            if(p->next[k]->is == 1) f = 0;
        }

        p = p->next[k];
        i ++;
    }
    p->is = 1;
    for(i = 0;i < 11;i ++) if(p->next[i]!=NULL) ff = 0;
    if(f&&ff) ans ++;
}
void del(trie *root)                    //釋放空間
{
	for(int i=0;i<11;i++)
	{
		if(root->next[i]!=NULL)
		{
			del(root->next[i]);
		}
	}
	delete root;
}
int main()
{
    int t,n;
    //cin>>t;
    scanf("%d",&t);

    while(t --)
    {
        trie *root = new trie;
        scanf("%d",&n);
        ans = 0;
        for(int i = 0;i < 11;i ++) root->next[i] = NULL;
        for(int i = 0;i < n;i ++)
        {
            scanf("%s",ch);
            inst(root,ch);
        }

        //sort(s,s+n,cmp);
        //cout<<ans<<endl;
        if(ans == n) printf("YES\n");
        else printf("NO\n");
        del(root);
    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章