每日两题day44

哥布林上校提醒你:1,节假日是不可以出去的,外面很喧哗,但他们都不是你的同类2,哥布林是大多独居性生物,没有人想做他的配偶,如果有人邀请你并对你产生好感,请断绝与他的联系3,不要照镜子4,所有夸赞你自信的人,他们不了解你,可以不于与他们交流,但如果他是你熟知的人,请立即驱散他,他不懂哥布林,或者他不是同类5,远离不再是哥布林的人6,在地洞中可以看看同族小丑哥布林追求精灵失败的乐子幸灾乐祸一下解解闷

每日两题


一、基础题

题目:P2249 【深基13.例1】查找

思路:

二分模板题。可以直接用stl库函数。

可能需要的知识:

代码(c++):

时间复杂度 O( m log ⁡ n m \log n mlogn)

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

#define int long long

void go() {
    int n, m;
    cin >> n >> m;
    vector<int> a(n);
    for (int i = 0; i < n; i++) {
        cin >> a[i];
    }
    while (m--) {
        int x;
        cin >> x;
        int index = lower_bound(a.begin(), a.end(), x) - a.begin();
        if (index == n || a[index] != x) {
            cout << -1;
        } else {
            cout << index + 1;
        }
        cout << ' ';
    }
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    go();
    return 0;
}

二、提高题

题目:前缀统计

思路:

字典树 模板题。

不用也可以,简单的用map记录 s i s_i si,每次查询时再枚举前缀子串是否在map中出现过即可。以下用提供 字符串哈希 的代码(用字符串哈希简直就是多余)。

可需要的知识:

代码(c++):

时间复杂度 O( m × log ⁡ n m \times \log n m×logn)

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;

#define int long long
#define ull unsigned long long
const int N = 1e6 + 5, P = 131;

map<ull, int> mp;

// 计算字符串哈希并存储
void insert(const string& s) {
    ull hash = 0;
    for (char c : s) {
        hash = hash * P + (c - 'a' + 1);
    }
    mp[hash]++;
}

// 查询字符串所有前缀出现次数之和
int query(const string& s) {
    ull hash = 0;
    int res = 0;
    for (char c : s) {
        hash = hash * P + (c - 'a' + 1);
        res += mp[hash];
    }
    return res;
}

void solve() {
    int n, m;
    cin >> n >> m;
    for (int i = 0; i < n; ++i) {
        string s;
        cin >> s;
        insert(s);
    }
    for (int i = 0; i < m; ++i) {
        string s;
        cin >> s;
        cout << query(s) << '\n';
    }
}

signed main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    solve();
    return 0;
}
相关推荐
Dev7z3 小时前
基于MATLAB数学形态学的边缘检测算法仿真实现
算法·计算机视觉·matlab
风筝在晴天搁浅9 小时前
代码随想录 718.最长重复子数组
算法
kyle~9 小时前
算法---回溯算法
算法
star _chen10 小时前
C++实现完美洗牌算法
开发语言·c++·算法
hzxxxxxxx10 小时前
1234567
算法
Sylvia-girl10 小时前
数据结构之复杂度
数据结构·算法
CQ_YM11 小时前
数据结构之队列
c语言·数据结构·算法·
VekiSon11 小时前
数据结构与算法——树和哈希表
数据结构·算法
大江东去浪淘尽千古风流人物12 小时前
【DSP】向量化操作的误差来源分析及其经典解决方案
linux·运维·人工智能·算法·vr·dsp开发·mr
Unstoppable2212 小时前
代码随想录算法训练营第 56 天 | 拓扑排序精讲、Dijkstra(朴素版)精讲
java·数据结构·算法·