0
点赞
收藏
分享

微信扫一扫

Python Pandas DataFrame对象 索引列的相关操作 (第7讲)

知识概览(哈希表)

例题展示

题目链接

https://www.acwing.com/problem/content/842/

代码(拉链法)

#include <iostream>
#include <cstring>

using namespace std;

const int N = 100010;

int h[N], e[N], ne[N], idx;

void insert(int x)
{
    int k = (x % N + N) % N;
    e[idx] = x;
    ne[idx] = h[k];
    h[k] = idx++;
}

bool query(int x)
{
    int k = (x % N + N) % N;
    for (int i = h[k]; i != -1; i = ne[i])
        if (e[i] == x)
            return true;
    
    return false;
}

int main()
{
    int n;
    scanf("%d", &n);
    
    memset(h, -1, sizeof h);
    
    while (n--)
    {
        char op[2];
        int x;
        scanf("%s%d", op, &x);
        
        if (*op == 'I') insert(x);
        else
        {
            if (query(x)) puts("Yes");
            else puts("No");
        }
    }
    
    return 0;
}

代码(开放寻址法)

#include <iostream>
#include <cstring>

using namespace std;

const int N = 200003, null = 0x3f3f3f3f;  // 数组长度设置为题目数据范围的2~3倍且是质数

int h[N];

int find(int x)
{
    int k = (x % N + N) % N;
    
    while (h[k] != null && h[k] != x)
    {
        k++;
        if (k == N) k = 0;
    }
    
    return k;
}

int main()
{
    int n;
    scanf("%d", &n);
    
    memset(h, 0x3f, sizeof h);
    
    while (n--)
    {
        char op[2];
        int x;
        scanf("%s%d", op, &x);
        
        int k = find(x);
        if (*op == 'I') h[k] = x;
        else
        {
            if (h[k] != null) puts("Yes");
            else puts("No");
        }
    }
    
    return 0;
}

知识概览(字符串哈希)

例题展示

题目链接

https://www.acwing.com/problem/content/843/

题解

代码

#include <iostream>

using namespace std;

typedef unsigned long long ULL;

const int N = 100010, P = 131;

int n, m;
char str[N];
ULL h[N], p[N];

ULL get(int l, int r)
{
    return h[r] - h[l - 1] * p[r - l + 1];
}

int main()
{
    scanf("%d%d%s", &n, &m, str + 1);
    
    p[0] = 1;
    for (int i = 1; i <= n; i++)
    {
        p[i] = p[i - 1] * P;
        h[i] = h[i - 1] * P + str[i];
    }
    
    while (m--)
    {
        int l1, r1, l2, r2;
        scanf("%d%d%d%d", &l1, &r1, &l2, &r2);
        
        if (get(l1, r1) == get(l2, r2)) puts("Yes");
        else puts("No");
    }
    
    return 0;
}

参考资料

  1. AcWing算法基础课
举报

相关推荐

Pandas——DataFrame常见操作

0 条评论