每日两题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;
}
相关推荐
不穿格子的程序员2 小时前
从零开始写算法——二分-搜索二维矩阵
线性代数·算法·leetcode·矩阵·二分查找
Kuo-Teng3 小时前
LeetCode 19: Remove Nth Node From End of List
java·数据结构·算法·leetcode·链表·职场和发展·list
Kuo-Teng3 小时前
LeetCode 21: Merge Two Sorted Lists
java·算法·leetcode·链表·职场和发展
2301_800399723 小时前
stm32 printf重定向到USART
java·stm32·算法
顾安r4 小时前
11.15 脚本算法 加密网页
服务器·算法·flask·html·同态加密
前端小L5 小时前
图论专题(四):DFS的“回溯”之舞——探寻「所有可能路径」
算法·深度优先·图论
司铭鸿5 小时前
数学图论的艺术:解码最小公倍数图中的连通奥秘
运维·开发语言·算法·游戏·图论
元亓亓亓5 小时前
LeetCode热题100--39. 组合总和
算法·leetcode·职场和发展
2401_841495645 小时前
【LeetCode刷题】找到字符串中所有字母异位词
数据结构·python·算法·leetcode·数组·滑动窗口·找到字符串中所有字母异位词