50237. String Cubic Pairing Task with Hash Table

難度:4.7/5

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define left(x) (2 * (x))
#define right(x) (2 * (x) + 1)
#define parent(x) ((x) / 2)
#define swap(x, y) {int t = (x); (x) = (y); (y) = t;}
#define max(x, y) ((x) > (y) ? (x) : (y))

typedef struct{
char s[6];
} string;

int n, k, c = 10;
string arr[100 * 100 * 100];
static inline int get_id(int i, int j, int k){ return i * 10000 + j * 100 + k;}

typedef struct{
int pos[100 * 100][10];
} hash_table;

static inline int f(string str){
int ans = 0;
for(int i = 0; str.s[i] != '\0'; i++){
ans = (ans * 29 + (str.s[i] - 'a' + 1)) % k;
}
return ans % k;
}

int find(hash_table* h, string str, int hash_val){
int now_pos;
for(int i = 0; i < c; i++){
now_pos = h->pos[hash_val][i];
if(now_pos == -1) continue;
if(strcmp(arr[now_pos].s, str.s) == 0){
h->pos[hash_val][i] = -1;
return now_pos;
}
}
return -1;
}
void insert(hash_table* h, int p, int hash_val){
for(int i = 0; i < c; i++){
if(h->pos[hash_val][i] == -1){
h->pos[hash_val][i] = p;
return;
}
}
}

void query(hash_table* h, int pos){
// printf("querying pos %d, %s\n", pos, arr[pos].s);
int hash_val = f(arr[pos]);
int rtv = find(h, arr[pos], hash_val);

if(rtv != -1){
printf("%s\n", arr[pos].s);
if(pos / 10000 + 1 < n) query(h, pos + 10000);
if(rtv / 10000 + 1 < n)query(h, rtv + 10000);
}
else{
insert(h, pos, hash_val);
}
}

int main(){
scanf("%d", &n);
k = n * n;
for(int i = 0; i < n; i++){
for(int j = 0; j <= i; j++){
for(int k = 0; k <= i; k++){
scanf("%s", arr[get_id(i, j, k)].s);
}
}
}

hash_table* h = (hash_table*) malloc(sizeof(hash_table));
memset(h->pos, -1, sizeof(h->pos));

for(int i = 0; i < n; i++){
for(int j = 0; j < n; j++){
query(h, get_id(max(i, j), i, j));
}
}
}

50237. String Cubic Pairing Task with Hash Table
https://aaronlin1229.github.io/judgegirl_50237/
Author
Akizumi
Posted on
July 17, 2023
Licensed under