数据结构与算法题目集(中文) - 7-14 电话聊天狂人(25 分)

本文介绍了一种使用自定义Hash规则进行电话号码统计的方法。通过结构体数组和链表实现高效的电话号码查找与计数,解决电话号码重复统计的问题。

题目链接:点击打开链接

题目大意:

解题思路:hash,自定义hash规则 + 结构体数组 + 结构体中的每个链表。

AC 代码

#include<bits/stdc++.h>
#include<cmath>

#define mem(a,b) memset(a,b,sizeof a);
#define INF 0x3f3f3f3f

using namespace std;

typedef long long ll;

const int maxn=1e5+100;

ll mi_tel,ma_Cnt;
int mergeCnt;

struct node
{
    ll tel;
    int cnt;
    node *next;
}nds[maxn];

void init()
{
    ma_Cnt=0;
    mergeCnt=1;
    mi_tel=LLONG_MAX;

    for(int i=0;i<maxn;i++)
    {
        nds[i].tel=-1;
        nds[i].cnt=0;
        nds[i].next=NULL;
    }
}

node * findTel(ll tel)
{
    node * nd;
    // 自定义hash规则
    // TEL:130 0571 1862
    // -> tel[9] + tel[10] + tel[7] + tel[1] + tel[2]
    // -> 62130
    int idx=0;
    idx+=tel%100;
    idx=idx*10+tel/10000%10;
    idx=idx*100+tel/100000000%100;
//    cout<<"idx = "<<idx<<endl;

    nd=&nds[idx];
    if(nd->tel==-1)
    {
        nd->tel=tel;
        return nd;
    }

    while(nd->tel!=tel)
    {
        if(nd->next==NULL)
        {
            nd->next=(node*)malloc(sizeof(node));
            nd=nd->next;
            nd->next=NULL;
            nd->tel=tel;
            nd->cnt=0;
            break;
        }
        else
            nd=nd->next;
    }

    return nd;
}

void insert(ll tel)
{
    node * nd=findTel(tel);
    nd->cnt++;
    if(nd->cnt>ma_Cnt)
    {
        ma_Cnt++;
        mergeCnt=1;
        mi_tel=tel;
    }
    else if(nd->cnt==ma_Cnt)
    {
        mergeCnt++;
        if(tel<mi_tel) mi_tel=tel;
    }
}

int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        init();
        ll tel1,tel2;
        for(int i=0;i<n;i++)
        {
            scanf("%lld%lld",&tel1,&tel2);
            insert(tel1);
            insert(tel2);
        }

        printf("%lld %d",mi_tel,ma_Cnt);
        if(mergeCnt>1) printf(" %d",mergeCnt);
        puts("");
    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

陆克和他的代码

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值