-
Notifications
You must be signed in to change notification settings - Fork 0
/
tt.hpp
113 lines (91 loc) · 2.82 KB
/
tt.hpp
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
#pragma once
#include <bits/stdc++.h>
#include "common.hpp"
#include "board.hpp"
using namespace std;
#define CHECK_COLLISION
#ifdef CHECK_COLLISION
struct alignas(128) TTEntry {
u64 area;
u64 bbs[14];
#else
struct TTEntry {
#endif
u8 depth; // 1-based, 0ならエントリが無効
};
class TranspositionTable {
public:
#ifdef CHECK_COLLISION
static constexpr size_t BUCKET_COUNT = 1ULL << 24;
#else
static constexpr size_t BUCKET_COUNT = 1ULL << 30;
#endif
TranspositionTable()
: bucket_(reinterpret_cast<TTEntry*>(aligned_alloc(128,sizeof(TTEntry)*BUCKET_COUNT)))
{
// どうせ探索開始時に clear() するので
//clear();
}
~TranspositionTable() {
free(bucket_);
}
void clear() noexcept {
memset(bucket_, 0, sizeof(TTEntry)*BUCKET_COUNT);
}
// 探索を打ち切ってよければ true を返す
// そうでない場合、適当にテーブルを更新して false を返す
bool check(int depth, u64 area, const u64 (&bbs)[TL_COUNT]) noexcept {
u64 idx = hash_position(area, bbs) & (BUCKET_COUNT-1);
auto& entry = bucket_[idx];
auto write_entry = [depth,area,&bbs,&entry]() noexcept {
#ifdef CHECK_COLLISION
entry.area = area;
memcpy(entry.bbs, bbs, 8*TL_COUNT);
#endif
entry.depth = u8(depth + 1);
};
// エントリが空なら現局面を格納して探索続行
if(entry.depth == 0) {
write_entry();
return false;
}
// エントリの深さが depth より大きければ現局面で上書きし、探索続行
if(depth < entry.depth-1) {
write_entry();
return false;
}
// エントリの深さが depth 以下のため、探索を打ち切れる可能性がある
#ifdef CHECK_COLLISION
// ハッシュ衝突した場合何もせず探索続行(深さの小さい局面を残す)
bool same = area == entry.area &&
equal(begin(bbs), end(bbs), begin(entry.bbs), end(entry.bbs));
if(!same) return false;
#endif
return true;
}
size_t entry_count() const noexcept {
return count_if(bucket_, bucket_+BUCKET_COUNT, [](const auto& e) noexcept {
return e.depth != 0;
});
}
private:
static u64 hash_position(u64 area, const u64(&bbs)[TL_COUNT]) noexcept {
u64 h = area;
for(auto bb : bbs) {
h = hash_combine(h,bb);
}
return h;
}
static u64 hash_combine(u64 h, u64 x) noexcept {
static constexpr u64 M = 0xc6a4a7935bd1e995;
static constexpr int R = 47;
x *= M;
x ^= x >> R;
x *= M;
h ^= x;
h *= M;
h += 0xe6546b64;
return h;
}
TTEntry* const bucket_;
};