方法一、先排序,前缀子串肯定是与父串挨着的

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int cmp(const void *a, const void *b)
{
    return strcmp((char*)a, (char*)b);
}

int main(int argc, char *argv[])
{
    int num, n;
    char tel[10005][11];
    scanf("%d", &num);

    while (num--) {
        int i, flag = 1;
        scanf("%d", &n);
        for (i = 0; i < n; ++i)
            scanf("%s", tel[i]);

        qsort(tel, n, sizeof(char) * 11, cmp);

        for (i = 1; i < n; ++i) {
            int len1 = strlen(tel[i-1]);
            int len2 = strlen(tel[i]);
            int j = 0;
            if (len1 <= len2) {
                while(tel[i-1][j] == tel[i][j] && j < len1)
                    ++j;
                if (j == len1)
                    flag = 0;
            }
            if (!flag)
                break;
        }
        if (flag)
            printf("YES\n");
        else
            printf("NO\n");
    }
    return 0;
}

方法二、传统trie树

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
#include<iostream>
using namespace std;
int cases, count;
int nodenum;

struct node
{
    bool isExist;
    node * branch[10];
}Node[100000];

class Trie
{
private:
    node root;
public:
    Trie(){root = Node[0];}
    bool insert(char num[])
    {
        node *location = &root;
        int i = 0;
        int len = strlen(num);
        while(num[i])
        {
            if(i==len-1 && location->branch[num[i]-'0'] != NULL)
            {
                return false;
            }
            if(location->branch[num[i]-'0']==NULL)
            {
                location->branch[num[i]-'0'] = &Node[nodenum];
                Node[nodenum].isExist = false;
                memset(Node[nodenum].branch,NULL,sizeof(Node[nodenum].branch));
                nodenum++;
            }
            if(location->branch[num[i]-'0']->isExist == true)
            {
                return false;
            }
            location = location->branch[num[i]-'0'];
            i++;
        }
        location->isExist = true;
        return true;
    }
};

int main()
{
    scanf("%d",&cases);
    while(cases--)
    {
        nodenum = 1;
        bool flag = true;
        scanf("%d",&count);
        char tel[11];
        Trie t;
        while(count--)
        {
            scanf("%s",tel);
            if(!t.insert(tel))
            {
                flag = false;
            }
        }
        if(flag)
        {
            printf("YES\n");
        }
        else
        {
            printf("NO\n");
        }
    }
    return 0;
}