hash map

#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif

#include<stdio.h>
#include<iostream>
using namespace std;

#define MAX_MUSIC_LEN (200)
#define SAMPLE_DATA_LEN (8)

static int seed, n, max_len, query_cnt;
static int music_db[10005][MAX_MUSIC_LEN];
static int music_len[10005];

static int pseudo_rand(void);
static void make_music_db(void);
static bool make_sample_with_noise(void);

extern void init(int total_music_cnt);
extern void send_music_db_data(int music_id, int music_len, int data[MAX_MUSIC_LEN]);
extern int find_music_id(int data[SAMPLE_DATA_LEN]);

///////////////////////////////////////////
#define rint register int
#define MAX_MUSIC_LEN (200)
#define SAMPLE_DATA_LEN (8)
#define MAXL (500000+1)

#define ABS(a) (((a)>0)? (a):(-a))
int noise[8];

int head[MAXL];
int mode = MAXL;
typedef struct Song{
int id;
int seq;
int data[8];
int len;
int next;
}SONG;
SONG snode[200 * 10000 + 1];
int use = 1;

#define HASHN 3 //number of data[] to hash

//debug
int dfscount = 0; //DFS times
int conflict = 0; //hash conflicts

int hfunc(int data[8])
{
int h = 0;
for (rint i = 0; i < HASHN; i++)
{
h = (h * 131 + ((data[i] >> 8) & 0xff)) % mode;
}
return h;
}

void insert(int music_id, int music_len, int data[MAX_MUSIC_LEN])
{
int h;
for (rint i = 0; i <= music_len - SAMPLE_DATA_LEN; i++)
{
snode[use].id = music_id;
snode[use].len = music_len;
snode[use].seq = i;
h = hfunc(&data[i]);
for (rint j = 0; j <SAMPLE_DATA_LEN; j++)
snode[use].data[j] = data[i + j];

snode[use].next = head[h];
head[h] = use;
use++;
}
}
int compare(int music[8], int noise[8])
{
for (rint i = 0; i < 8; i++) //Compare
{
if (music[i] + 127 < noise[i] || music[i] - 128 > noise[i])
return 0;
}
return 1;
}

int find(int h, int data[8])
{
int index = 0;
for (index = head[h]; index != 0; index = snode[index].next)
{
conflict++;
if (compare(snode[index].data, data) == 1)
return snode[index].id;
}
return 0;
}

void init(int total_music_cnt)
{
SONG s = { 0 };
for (rint i = 0; i < MAXL; i++)
{
head[i] = 0;
snode[i] = s;
}
use = 1;
}

void send_music_db_data(int music_id, int music_len, int data[MAX_MUSIC_LEN])
{
insert(music_id, music_len, data);
}


int dfsfind(int data[SAMPLE_DATA_LEN], int level)
{
if (level >= HASHN) {
int h = hfunc(data);
int ret = find(h, noise);
return ret;
}

for (int i = 0; i < 3; i++)
{
if (i == 0)
data[level] = noise[level]; //orgin
if (i == 1)
{
data[level] = noise[level] - 0x100; //-1
}
if (i == 2)
{
data[level] = noise[level] + 0x100; //+1
}
dfscount++;
// printf("level %d, type %d ++ times %d\n", level, i, count++);
int ret = dfsfind(data, level + 1);
if (ret > 0)
return ret;
}
return 0;
}

int find_music_id(int data[SAMPLE_DATA_LEN])
{
for (rint i = 0; i < 8; i++)
noise[i] = data[i];

int ret = dfsfind(data, 0);
// printf("times %d confict %d\n", count, conflict);
return ret;
}

//////////////////////////////////////////

posted @ 2019-01-11 15:45  调皮的贝叶斯  阅读(98)  评论(0)    收藏  举报