哈希技术

哈希技术

哈希技术应用广泛,可用于判重,存取,查询,降低时间复杂度;

哈希可用STL中的set代替

哈希可用STL中的set
set<int> ss;
ss.insert(t); //插入
if(ss.find(a)!=ss.end())... //找到
ss.clear(); //清空
STL_set

哈希模版

const int HM=999983;  //采用质数可减小冲突

struct Hash
{
    long long date;
    Hash *next;
};Hash h[HM];

int h(long long date)
{
    int res=0;
    ....//随便算,位运算和加法比乘法更省时
    return abs(res)%maxn;
}

void insert(long long date,Hash *H)
{
    int key=h(date);    //哈希函数;
    Hash *pre=&H[key],*p=pre->next;
    while(p!=NULL){
        if(p->date=date) return;
        pre=p;
        p=p->next;
    }
    p=(Hash*)malloc(sizeof(Hash));
    p->date=date;p->next=NULL;  //注意此处要将p->next置空,否则runtime error
    pre->next=p;
}

bool find(long long date,Hash *H)
{
    int key=h(date);
    Hash *pre=&H[key],*p=pre->next;
    while(p!=NULL){
        if(p->date==date) return true;
        pre=p;
        p=p->next;
    }
    return false;
}

void Init(Hash *H) //初始化或清空哈希表
{
    memset(H,NULL,sizeof(H));
}
hash模版

显然,哈希比STL效率高得多

没有AC不了的题,只有不努力的ACMER!
原文地址:https://www.cnblogs.com/--560/p/4330206.html