poj 3630

题意:给出n个数字串,问其中是否有一个串是另一个串的前缀。(静态建树的模板)

 

思路:基础的Trie。必须使用静态建树,否则会超时。还有就是有可能是前面的串是后面的串的前缀,也有可能后面的串是前面的串的前缀,如:

2
2
1
12
2
12
1

代码如下:

#include<iostream>
using namespace std;
const int Max = 100000;
const int branchNum = 10;

struct tree_node
{
    bool isstr;
    tree_node *next[branchNum];
}root, node[Max];
int p;
bool flag;

void insert(char *word)
{
    bool new_flag = false;
    tree_node *location = &root;
    while(*word)
	{
        if(location->isstr == true)
		{     // 前面的串为word的前缀。
            flag = false;
            return;
        }
        if(location->next[*word-'0']==NULL)
		{
            new_flag = true;             //  有新的节点开辟,证明word不为前面的串的前缀。
            node[p].isstr = false;       //   新节点的初始化。
            memset(node[p].next, NULL, sizeof(node[p].next));         
            location->next[*word-'0'] = &node[p ++];
        }
        location = location->next[*word-'0'];
        word++;
    }
    location->isstr = true;
    if(!new_flag) 
		flag = false;          // word为前面的串的前缀。
}

int main()
{
    int t, n;
    scanf("%d", &t);
    while(t--)
	{
        scanf("%d", &n);
        p = 0;
        flag = true;
        memset(root.next, NULL, sizeof(root.next));  //  记得每次都得做root的初始化,WA在这。
        while(n--)
		{
            char word[11];
            scanf("%s", word);
            if(flag) 
				insert(word);
        }
        if(flag) 
			printf("YES\n");
        else 
			printf("NO\n");
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值