MLE与数组大小无关(本人想练习手写hash)
#include <cmath>
#include <vector>
#include <string>
#include <iostream>
#include <algorithm>
using namespace std;
const int mod = 99997;
struct edge {
string name, fa;
edge() : name(""), fa("") {}
};
string str, fa;
vector<string> ship;
vector<edge> node(mod + 10);
int get_hash(string &s) {
int hash = 0, w = 1;
for (char &c: s) {
hash += (tolower(c) - 'a') * w;
w *= 26;
}
return hash % mod;
}
void solve(string &son) {
int hash_son = get_hash(son);
node[hash_son].fa = fa;
node[hash_son].name = son;
}
string found(string &s) {
int hash = get_hash(s);
if (node[hash].fa == node[hash].name) return s;
return node[hash].fa = found(node[hash].fa);
}
int main() {
freopen("T,in", "r", stdin);
freopen("T.out", "w", stdout);
ios::sync_with_stdio(false);
cin.tie(0);
while (cin >> str) {
if (str == "$") break;
char op = str[0];
str = str.substr(1);
if (op == '#') {
int hash = get_hash(str);
fa = str;
node[hash].name = str;
if (node[hash].fa == "") node[hash].fa = str;
} else if (op == '+') solve(str);
else cout << str << ' ' << found(str) << '\n';
}
return 0;
}