初学哈希表菜鸡求助,只过了第一个点
查看原帖
初学哈希表菜鸡求助,只过了第一个点
896371
xduliu楼主2024/10/8 19:56
#include<cstring>
#include<cstdio>
using namespace std;
int main()
{
    int n,i,hash,t[233335]={0},to[233335]={0},num=0;//t为每个字符串的个数,to为字符串所对应的字符串,均使用哈希值
    string s1,s2;
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
        cin>>s1>>s2;
        if(s1[0]==s2[0]&&s1[1]==s2[1])//特判
            continue;
        hash=((s1[0]-'A')+(s1[1]-'A')*26+(s2[0]-'A')*26*26+(s2[1]-'A')*26*26*26)%233333;//字符串由城市和州的前两个字符组成        
        if(!t[hash])//如果当前字符串不存在,则计算对应字符串哈希值,否则只加个数
            to[hash]=((s2[0]-'A')+(s2[1]-'A')*26+(s1[0]-'A')*26*26+(s1[1]-'A')*26*26*26)%233333;
        t[hash]++;
        num+=t[to[hash]];//加上对应字符串的个数,这样只用加一次,不会重复
    }
    printf("%d",num);
    return 0;
}```
2024/10/8 19:56
加载中...