诶学习了一下有根树的哈希方法
还不是很懂无根树要怎么哈希
#include <iostream>
#include <cstdio>
#include <stack>
#include <map>
#include <cstdlib>
#include <cstring>
#define N 3050
using namespace std;
typedef unsigned long long uLL;
int h[N],cnt,cur,n,tot;
uLL p[N];
char s[N];
map<uLL,uLL> mp;
stack<int> sta;
struct Edge{ int b,n; }e[2*N];
void link(int a,int b) {
// printf("%d %d\n",a,b);
e[++cnt].b = b, e[cnt].n = h[a], h[a] = cnt;
e[++cnt].b = a, e[cnt].n = h[b], h[b] = cnt;
}
uLL rnd() { return (uLL)rand() * rand() * rand() * rand(); }
uLL dfs(int u,int f) {
uLL now = 1LL;
for (int i=h[u],v;v=e[i].b,i;i=e[i].n) {
if (v == f) continue;
now += p[ dfs(v,u) ];
}
if (mp[now]) return mp[now];
mp[now] = ++tot;
return tot;
}
uLL get() {
n = strlen(s+1);
for (int i=1;i<=cnt;i++) h[i]=0;
cnt = 0; cur = 1;
sta.push(1);
for (int i=1;i<=n;i++) {
if (s[i] == '0') {
++cur;
if (!sta.empty()) link(sta.top(),cur);
sta.push(cur);
} else sta.pop();
}
return dfs(1,1);
}
int main() {
srand(19930726);
for (int _=0;_<N;_++) p[_] = rnd();
int T=0; scanf("%d",&T);
while (T--) {
scanf("%s",s+1);
uLL p1 = get();
scanf("%s",s+1);
uLL p2 = get();
puts(p1==p2?"same":"different");
}
return 0;
}