数据结构(二)

Trie

凡是用trie来做的题,题目一定限制了字母的种类是26个或者52个
在这里插入图片描述

例题:

#include<iostream>

using namespace std;

const int N = 100010;

int son[N][26],cnt[N],idx; //下标是0的点,既是根节点,又是空节点
char str[N];
//idx可以理解成每个节点的编号

void insert(char str[])
{
    int p = 0;  //从根节点开始插入
    for(int i = 0;str[i];i++)
    {
        int u = str[i] - 'a';
        if(!son[p][u]) son[p][u]= ++idx;
        p=son[p][u];
    }
    
    cnt[p] ++ ;
}

int query(char str[])
{
    int p = 0;
    for(int i = 0;str[i];i++)
    {
        int u = str[i] - 'a';
        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];
        scanf("%s%s",op,str);
        if(op[0] == 'I') insert(str);
        else printf("%d\n",query(str));
    }
    return 0;
}

并查集

1.将两个集合合并
2.询问两个元素是否在一个集合当中

基本原理:每个集合用一颗树来表示。树根的编号就是整个集合的编号。每个节点存储它的父节点,p[x]表示x的父节点。

问题1:如何判断树根:if (p[x] == x)
问题2:如何求x的集合编号:while (p[x] != x) x = p[x];
问题3:如何合并两个集合:px是x的集合编号,py是y的集合编号。p[x] = y;

例题:

#include<iostream>
using namespace std;

int n,m;

const int N = 100010;
int p[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;
    
    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;
}

基本模板要素:记录堆中元素的h[N]、记录堆中元素个数的cnt、用递归写的down函数、用while循环写的up函数
例题1:

#include<iostream>
#include<algorithm>

using namespace std;

const int N = 1e5+10;

int n,m;
int h[N],cnt;

void down(int u)
{
    int t=u;
    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(u != t)
    {
        swap(h[u],h[t]);
        down(t);
    }
}

void up(int u)
{
    while(u / 2 && h[u / 2] > h[u])
    {
        swap(h[u / 2],h[u]);
        u /= 2;
    }
}

int main()
{
    scanf("%d%d",&n,&m);
    for(int i=1;i<=n;i++) scanf("%d",&h[i]);
    cnt = n;
    for(int i=n/2;i;i--) down(i);//堆的构建

    while(m --)
    {
        printf("%d ",h[1]);
        h[1] = h[cnt];
        cnt--;
        down(1);
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值