[字符串哈希] lg-P3405. 省市Cities and States(字符串哈希+USACO2016)

1. 题目来源

链接:P3405 [USACO16DEC]Cities and States S

相关题目:[字符串哈希+模板]字符串哈希

2. 题目解析

字符串哈希的基本应用,重点在数据组织上了。

且本题花里胡哨做法很多,map 当然也是个很好的选择。可以看看题解区大佬的各种做法。

拿出前两位字符组织成一个长度为 4 的字符串,进行字符串哈希映射,在 vector 中依旧模拟开散列,哈希取模值作为下标,哈希值作为字符串唯一标识,记录出现个数。

注意题目要求处于同一洲的两城市并不计算在内。

其实这样的数据组织就是一个 unordered_map 了。

代码:

// https://www.luogu.com.cn/problem/P3405

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <string>

using namespace std;

typedef long long LL;

const int N = 5, MOD = 23333;

int n;
char a[N], b[N];
LL res;
vector<pair<int, int> > h[MOD + 5];       // 哈希取模值---原哈希值,出现次数

int get(char a[], char b[]) {
    return (a[0] - 'A') * 26 + (a[1] - 'A') * 26 * 26 + 
           (b[0] - 'A') * 26 * 26 * 26 + (b[1] - 'A') * 26 * 26 * 26 * 26; 
}

void insert(int x) {
    for (int i = 0; i < h[x % MOD].size(); i ++ ) {
        if (h[x % MOD][i].first == x) {
            h[x % MOD][i].second ++ ;
            break;
        } 
    }
    h[x % MOD].push_back(make_pair(x, 1));
}

int find(int x) {
    for (int i = 0; i < h[x % MOD].size(); i ++ ) 
        if (h[x % MOD][i].first == x) 
            return h[x % MOD][i].second;
    return 0;
}

int main() {
    scanf("%d", &n);
    for (int i = 0; i < n; i ++ ) {
        scanf("%s%s", a, b);
        if (a[0] == b[0] && a[1] == b[1]) continue;     // 相同城市不计算在内
        res += find(get(b, a));
        insert(get(a, b));
    }
    printf("%lld\n", res);
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ypuyu

如果帮助到你,可以请作者喝水~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值