字符串-字典树_求一个字符串的所有子串

字符串-字典树_求一个字符串的所有子串HDU-1251统计难题POJ-3603PhoneListAcWing-143最大异或对HDU-5536ChipFactory字典树,顾名思义是以树结构来模拟字典。回想我们查字典的过程,比如查找”man”,先翻到字典m部分,再翻第二个字母a和第三个字母n,一共查找3次。查找次数最多是等于个单词的长度。插入查找单词的时间复杂度时O(m)O(m),此外有公共前缀的单词只需存一次公共前缀,节省了空间。

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE使用 1年只要46元 售后保障 童叟无欺

字典树


字典树(Trie),顾名思义是以树结构来模拟字典。回想我们查字典的过程,比如查找”man”,先翻到字典m部分,再翻第二个字母a和第三个字母n,一共查找3次。查找次数最多是等于个单词的长度。插入查找单词的时间复杂度时 O ( m ) O(m) O(m),此外有公共前缀的单词只需存一次公共前缀,节省了空间,也可理解为前缀树。

根结点不包含字符,根结点外每个结点包含一个字符,从根结点到某子结点路径上经过的字符,连起来就是该结点对应的字符串,每个结点的字符串互不相同。
如图所示是单词hi,he,heat,man,may的字典树。代码实现时会在结点设标识表示是否为单词结尾,如图中下划线。
在这里插入图片描述
字典树应用

  1. 字符串检索
    查询检索字符串
  2. 词频统计
    统计一个单词出现了多少次
  3. 字符串排序
    字典树建好后,先序遍历就得到了排序。
  4. 前缀匹配
    根据前缀,用于搜索提示等

例题


HDU-1251统计难题

HDU-1251统计难题

Problem Description
Ignatius最近遇到一个难题,老师交给他很多单词(只有小写字母组成,不会有重复的单词出现),现在老师要他统计出以某个字符串为前缀的单词数量(单词本身也是自己的前缀).
Input
输入数据的第一部分是一张单词表,每行一个单词,单词的长度不超过10,它们代表的是老师交给Ignatius统计的单词,一个空行代表单词表的结束.第二部分是一连串的提问,每行一个提问,每个提问都是一个字符串.
注意:本题只有一组测试数据,处理到文件结束.
Output
对于每个提问,给出以该字符串为前缀的单词的数量.
Sample Input
banana
band
bee
absolute
acm
(换行)
ba
b
band
abc
Sample Output
2
3
1
0

分析:
字典树模板题,将单词全部插入字典树,维护经过次数 n u m [ ] num[] num[],再输出前缀单词对应经过次数即可。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 1000006;
int trie[maxn][26]; //26叉字典树,存储值为对应子节点位置(编号)
int num[maxn] = { 
    0 }; //某前缀单词的数量
int pos = 1; //新分配的存储位置,可理解为结点编号
void insert(char s[]) { 
    //向字典树插入单词
    int p = 0; //从根结点开始
    for (int i = 0; s[i]; i++) { 
   
        int n = s[i] - 'a';
        if (trie[p][n] == 0) //对应字符还没有值则新分配
            trie[p][n] = pos++;
        p = trie[p][n];
        num[p]++;
    }
}
int find(char s[]) { 
     //返回某字串为前缀的单词数量
    int p = 0;
    for (int i = 0; s[i]; i++) { 
   
        int n = s[i] - 'a';
        if (trie[p][n] == 0)
            return 0;
        p = trie[p][n];
    }
    return num[p];
}
int main(){ 
   
    char s[15];
    while (gets(s) && s[0] != '\0')
        insert(s);
    while (~scanf("%s", s))
        printf("%d\n", find(s));
    return 0;
}

POJ-3603Phone List

POJ-3603Phone List

Given a list of phone numbers, determine if it is consistent in the sense that no number is the prefix of another. Let’s say the phone catalogue listed these numbers:
Emergency 911
Alice 97 625 999
Bob 91 12 54 26
In this case, it’s not possible to call Bob, because the central would direct your call to the emergency line as soon as you had dialled the first three digits of Bob’s phone number. So this list would not be consistent.
Input
The first line of input gives a single integer, 1 ≤ t ≤ 40, the number of test cases. Each test case starts with n, the number of phone numbers, on a separate line, 1 ≤ n ≤ 10000. Then follows n lines with one unique phone number on each line. A phone number is a sequence of at most ten digits.
Output
For each test case, output “YES” if the list is consistent, or “NO” otherwise.
Sample Input
2
3
911
97625999
91125426
5
113
12340
123440
12345
98346
Sample Output
NO
YES

分析:
给若干字符串,问某字符串是否是另一字符串的前缀。依次将字符串插入字典树中并在末尾标记,当插入过程中遇到标记时,则说明遇到了它的前缀字串;否则检查是否有新分配存储位置 p o s pos pos,若没有新分配,则说明它是其它字串的前缀。

#include<cstdio>
#include<cstring>
using namespace std;
const int maxn = 100005;
int trie[maxn][10]; //0~9即十叉字典树
bool flag[maxn];//标记
int pos;
char s[20];
bool insert() { 
   
    int p = 0;
    bool isNew = false;
    for (int i = 0; s[i]; i++) { 
   
        int u = s[i] - '0';
        if (trie[p][u] == 0) { 
   
            trie[p][u] = pos++;
            isNew = true;
        }
        p = trie[p][u];
        if (flag[p])return false; //经过标记
    }
    flag[p] = true;
    return isNew;//没经过标记但处在其他串路径上
}
int main() { 
   
    int t, n;
    scanf("%d", &t);
    while (t--) { 
   
        memset(flag, false, sizeof(flag));
        memset(trie, 0, sizeof(trie));
        bool ans = true;
        pos = 1;
        scanf("%d", &n);
        for (int i = 0; i < n; i++) { 
   
            scanf("%s", s);
            if (ans && !insert())
                ans = false;
        }
        if (ans)puts("YES");
        else puts("NO");
    }
    return 0;
}

AcWing-143最大异或对

AcWing-143最大异或对

在给定的N个整数A1,A2……AN中选出两个进行xor(异或)运算,得到的结果最大是多少?
输入格式
第一行输入一个整数N。
第二行输入N个整数A1~AN。
输出格式
输出一个整数表示答案。
数据范围
1≤N≤105,
0≤Ai<231
输入样例:
3
1 2 3
输出样例:
3

分析:
求最大异或值,构建二叉字典树(01),把数字转换成二进制,从高位往地位,决策使路径尽可能不同(不同异或值才为1),遍历输出最优解。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 100005;
int trie[maxn * 100][2], num[maxn * 100];
int a[maxn], pos = 1;
void insert(int x) { 
   
    int p = 0;
    for (int i = 30; i >= 0; i--) { 
   
        int u = x >> i & 1;
        if (trie[p][u] == 0)
            trie[p][u] = pos++;
        p = trie[p][u];
    }
    num[p] = x;//结尾标记这条路对应的数值
}
int find(int x) { 
   
    int p = 0;
    for (int i = 30; i >= 0; i--) { 
   
        int u = x >> i & 1;
        if (trie[p][!u])p = trie[p][!u];//另一条路可以走
        else p = trie[p][u];//不能走则走相同的
    }
    return num[p] ^ x;
}
int main() { 
   
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) { 
   
        cin >> a[i];
        insert(a[i]);
    }
    int ans = 0;
    for (int i = 0; i < n; i++)
        ans = max(ans, find(a[i]));
    cout << ans << "\n";
    return 0;
}

HDU-5536Chip Factory

HDU-5536Chip Factory

Problem Description
John is a manager of a CPU chip factory, the factory produces lots of chips everyday. To manage large amounts of products, every processor has a serial number. More specifically, the factory produces n chips today, the i-th chip produced this day has a serial number si.
At the end of the day, he packages all the chips produced this day, and send it to wholesalers. More specially, he writes a checksum number on the package, this checksum is defined as below:
maxi,j,k(si+sj)⊕sk
which i,j,k are three different integers between 1 and n. And ⊕ is symbol of bitwise XOR.
Can you help John calculate the checksum number of today?
Input
The first line of input contains an integer T indicating the total number of test cases.
The first line of each test case is an integer n, indicating the number of chips produced today. The next line has n integers s1,s2,…,sn, separated with single space, indicating serial number of each chip.
1≤T≤1000
3≤n≤1000
0≤si≤109
There are at most 10 testcases with n>100
Output
For each test case, please output an integer indicating the checksum number in a line.
Sample Input
2
3
1 2 3
3
100 200 300
Sample Output
6
400

分析:
给定一个序列 s s s,要求找到三个不同的 i , j , k i,j,k i,j,k,使得 ( s [ i ] + s [ j ] ) (s[i]+s[j]) (s[i]+s[j]) xor s [ k ] s[k] s[k]的值最大。
类似上一题最大异或对,遍历 i , j i,j i,j,因为 i j k ijk ijk要不同,所以要先删掉 s [ i ] 、 s [ j ] s[i]、s[j] s[i]s[j],然后查询 s [ i ] + s [ j ] s[i]+s[j] s[i]+s[j],也是决策使路径尽量不同,更新最优解,然后回溯插入删掉的 s [ i ] 、 s [ j ] s[i]、s[j] s[i]s[j]
至于怎么删,其实插入时是 c n t [ ] cnt[] cnt[]++记录路径,删掉改成 c n t [ ] cnt[] cnt[]–即可。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 40004;
int trie[maxn][2], cnt[maxn], num[maxn];
int pos, k, a[1003];
void insert(int x) { 
   
    int p = 0;
    for (int i = 30; i >= 0; i--) { 
   
        int u = x >> i & 1;
        if (trie[p][u] == 0)
            trie[p][u] = pos++;
        p = trie[p][u];
        cnt[p]++;   //记录经过路径
    }
    num[p] = x;
}
void del(int x) { 
   
    int p = 0;
    for (int i = 30; i >= 0; i--) { 
   
        int u = x >> i & 1;
        p = trie[p][u];
        cnt[p]--;   //对应路径--
    }
}
int find(int x) { 
   
    int p = 0;
    for (int i = 30; i >= 0; i--) { 
   
        int u = x >> i & 1;
        //因为存在trie[p][!u]不为空(已分配位置),但是其路径已经删除了,所以不能用其判断
        //应该用cnt判断,这点和上一题不同
        if (cnt[trie[p][!u]])p = trie[p][!u];//优先选另一条路
        else p = trie[p][u];
    }
    return num[p] ^ x;
}
int main() { 
   
    int t, n;
    cin >> t;
    while (t--) { 
   
        memset(cnt, 0, sizeof(cnt));
        memset(num, 0, sizeof(num));
        memset(trie, 0, sizeof(trie));
        pos = 1;
        cin >> n;
        for (int i = 0; i < n; i++) { 
   
            cin >> a[i];    //插入进字典树
            insert(a[i]);
        }
        int ans = 0;
        for (int i = 0; i < n; i++) //遍历ij
            for (int j = i + 1; j < n; j++) { 
   
                del(a[i]);  //删除ij
                del(a[j]);
                ans = max(ans, find(a[i] + a[j]));
                insert(a[i]); //插入ij回溯
                insert(a[j]);
            }
        cout << ans << "\n";
    }
    return 0;
}

原创不易,请勿转载本不富裕的访问量雪上加霜
博主首页:https://blog.csdn.net/qq_45034708
如果文章对你有帮助,记得关注点赞收藏❤

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/196576.html原文链接:https://javaforall.net

(0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • python编程考试有哪些(python编程考试模拟题)

    python编程考试有哪些(python编程考试模拟题)2021国内外主流机器人编程赛事+等级考试Scratch编程、C++编程、Python编程等多个赛项,评比类、竞技类不同比赛形式自主选择。多个国内外主流机器人编程赛事,总能帮助孩子找到施展能力、表现创意的舞台。机器人、编程、人工智能等级考试篇全国青少年机器人技术等级考试和全国青少年软件编程等级考试均由中国电子…。2021机器人编程赛事+等级考试攻略之国内外主流赛事及能力测评篇上周,玛酷在公众号发布了一篇名为《2021机器人编程赛事+等级考试攻略之教育部白名单赛事篇》的文章。文章中为大家介绍了20

    2022年5月17日
    65
  • Couchbase vs Redis,究竟哪个更胜一筹?

    Couchbase vs Redis,究竟哪个更胜一筹?

    2022年2月19日
    46
  • 微信公众号开发之实现自定义微信公众号菜单和跳转第三方网页[通俗易懂]

    微信公众号开发之实现自定义微信公众号菜单和跳转第三方网页[通俗易懂]自定义菜单创建接口:http请求方式:POST(请使用https协议)https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN自定义菜单查询接口:http请求方式:GEThttps://api.weixin.qq.com/cgi-bin/menu/get?access_token=ACCES…

    2022年5月23日
    72
  • TC_P_Windows 安裝Eclipse

    TC_P_Windows 安裝Eclipse

    2021年8月6日
    55
  • XRay安装使用以及Burp联动

    XRay安装使用以及Burp联动0x00前言XRay是长亭科技洞鉴核心引擎中提取出的社区版漏洞扫描神器,属于一款功能十分强大的国产被动扫描工具,其应用范围涵括,Web通用漏洞扫描、被动代理扫描、社区POC集成……XRay的定位是一款安全辅助评估工具,而不是攻击工具,其内置的所有payload和poc均为无害化检查。毫不犹豫的说,XRay属于渗透测试人员安全渗透的一大神兵利器!可以想象,当Burp与XRay联动时,必将碰撞出不一样的火花!0x01下载XRay…

    2022年5月7日
    493
  • simsun是什么字体怎样改成中文_ttf 宋体

    simsun是什么字体怎样改成中文_ttf 宋体华文细黑:STHeitiLight[STXihei]华文黑体:STHeiti华文楷体:STKaiti华文宋体:STSong华文仿宋:STFangsong俪黑Pro:LiHeiProMediu

    2022年8月1日
    6

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号