1.Tire
1.1基本介绍
Trie树又称字典树、单词查找树。是一种能够高效存储和查找字符串集合的数据结构。
1.2用数组模拟
1.3例题:Trie字符串统计
法一:Tire数
#include<iostream>
using namespace std;
const int N = 100010;
int son[N][26];//Tire树中每个点的所有儿子
int cnt[N];//以当前这个点结尾的单词有多少个
int idx;//当前用到了哪个下标,下标是0的点,既是根节点又是空结点
char str[N];
void inert(char str[])
{
int p = 0;
for(int i = 0;str[i];i++)
{
int u = str[i] - 'a';//a---0,一种映射关系a-z ===》 0-25
if(!son[p][u]) son[p][u] = ++idx;
p = son[p][u];
}
cnt[p]++;//以p这个点结尾字符串加1
}
int query(char str[])
{
int p = 0;
for(int i = 0;str[i];i++)
{
int u = str[i] - 'a';//a---0,一种映射关系a-z ===》 0-25
if(!son[p][u]) return 0;
p = son[p][u];
}
return cnt[p];
}
int main()
{
int n;
scanf("%d",&n);
while(n--)
{
char op[2];
//首先说明 %s格式符 表示用来输入出一个字符串
//而字符串是以数组的形式的存储的
//c语言中数组名代表该数组的起始地址。
//此处,a为数组名 代表的是首地址,所以就不用取地址符了, 再用取地址符号 就重复了
scanf("%s%s",op,str);
if(op[0] == 'I') inert(str);
else printf("%d\n",query(str));
}
return 0;
}
法二:哈希表
#include<iostream>
#include<string>
#include<unordered_map>
using namespace std;
const int N = 20010;
int main() {
unordered_map<string, int> tb;
int n;
cin >> n;
while (n--) {
char op;
cin >> op;
if (op == 'I') {
string str;
cin >> str;
tb[str]++;
}
if (op == 'Q') {
string str;
cin >> str;
cout << tb[str] << endl;
}
}
return 0;
}
2.并查集
例题:合并集合
代码
#include<iostream>
using namespace std;
const int N = 100010;
int n,m;
int p[N];//father数组
int find(int x)//返回x所在集合的编号/祖宗节点 + 路径压缩(优化)
{
if(p[x] != x) p[x] = find(p[x]); //父节点等于祖宗节点
return p[x]; //返回父节点
}
int main()
{
scanf("%d%d",&n,&m);
//初始化
for(int i = 0;i < n;i++) p[i] = i;
while(m--)
{
char op[2];
int a,b;
scanf("%s%d%d",op,&a,&b);
if(op[0] == 'M') p[find(a)] = find(b);
else
{
if(find(a) == find(b)) puts("Yes");
else puts("No");
}
}
return 0;
}
例题:连通块中点的数量
代码
#include<iostream>
using namespace std;
const int N = 100010;
int n,m;
int p[N];//father数组
int cnt[N]; //每个集合当中点的个数
int find(int x)//返回x所在集合的编号/祖宗节点 + 路径压缩(优化)
{
if(p[x] != x) p[x] = find(p[x]); //父节点等于祖宗节点
return p[x]; //返回父节点
}
int main()
{
scanf("%d%d",&n,&m);
//初始化
for(int i = 1;i <= n;i++)
{
p[i] = i;
cnt[i] = 1;
}
while(m--)
{
char op[5];//为了过滤点空格和回车
int a,b;
//即使读入一个字符,也要使用%s来读
scanf("%s",op);
if(op[0] == 'C')
{
scanf("%d%d",&a,&b);
if(find(a) == find(b)) continue;
cnt[find(b)] += cnt[find(a)];
p[find(a)] = find(b);
}
else if(op[1] == '1')
{
scanf("%d%d",&a,&b);
if(find(a) == find(b)) puts("Yes");
else puts("No");
}
else
{
scanf("%d",&a);
printf("%d\n",cnt[find(a)]);
}
}
return 0;
}
3.堆
例题:堆排序
#include<iostream>
#include<algorithm>
using namespace std;
const int N = 100010;
int n,m;
int h[N],cnt;
void down(int u)
{
int t = u;//用t来存储最小值的下标
if(u * 2 <= cnt && h[u * 2] < h[t]) t = u * 2;
if(u * 2 + 1 <= cnt && h[u * 2 + 1] < h[t]) t = u * 2 + 1;
if(t != u)
{
swap(h[u],h[t]);
down(t);
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i = 1;i <= n;i++)
{
scanf("%d",&h[i]);
}
cnt = n;
//如何建堆,O(n)的建堆方式
for(int i = n / 2;i;i--) down(i);//构建一个堆
while(m--)
{
cout<<h[1]<<" ";
h[1] = h[cnt];
cnt--;
down(1);
}
}