Phone List (排序+字典树)

Phone List (排序+字典树)

题目大意:给出多组字符串,问是否有某一个字符串是另一个字符串的前缀,有的话输出NO,没有输出YES。

解题思路:把字符串按照长度从大到小排序一下,然后插入,看此串是否出现过。

Code:


#include <iostream>
#include <cstdio>
#include<cmath>
#include <cstring>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int N = 1e4+10;
string str[N];
int tree[N<<3][10],vis[N<<3],cnt = 1;

bool insert(string s){
    int n = s.size(),p = 1;
    for(int i = 0;i < n;i++){
        int x = s[i]-'0';
        if(!tree[p][x]) tree[p][x] = ++cnt;
        p = tree[p][x];
        vis[p]++;                     //出现过就+1
    }
//    for(int i = 0;i < 10;i++){
//        if(tree[p][i] != 0) return true;
//        tree[p][0] = -1;
//    }
//    return false;
	return vis[p]>1;            //根节点是否出现过两次以上
}
bool cmp(string a,string b){
    return a.size() > b.size();
}

void solve(int n){
    sort(str,str+n,cmp);
    for(int i = 0;i < n;i++){
        if(insert(str[i])){
            printf("NO\n");
            return;
        }
    }
    printf("YES\n");
}
int main(){
//	ios::sync_with_stdio(0);
//	cin.tie(0); cout.tie(0);
    int t;
    scanf("%d",&t);
    while(t--){
        int n;
        memset(tree,0,sizeof tree);
        memset(vis,0,sizeof vis);
        cnt = 1;
        scanf("%d",&n);
        for(int i = 0;i < n;i++){
            cin >> str[i];
        }
        solve(n);
    }
    return 0;
}


猜你喜欢

转载自blog.csdn.net/weixin_43872264/article/details/107619574
今日推荐