POJ1635【树的同构】【hash】

/* I will wait for you*/

#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <algorithm>
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <deque>
#include <map>
#include <set>
#include <string>
#define make make_pair
#define fi first
#define se second

using namespace std;

typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;

const int maxn = 10010;
const int maxm = 1010;
const int maxs = 26;
const int inf = 0x3f3f3f3f;
const int P = 19001;
const double error = 1e-9;

inline int read()
{
	int x = 0, f = 1;
	char ch = getchar();
	while (ch <= 47 || ch >= 58)
		f = (ch == 45 ? -1 : 1), ch = getchar();
	while (ch >= 48 && ch <= 57)
		x = x * 10 + ch - 48, ch = getchar();
	return x * f;
}

char s[maxn], t[maxn];

struct edge
{
	int v, next;
} e[maxn];

int T, cnt, sum, head[maxn], ran[maxn], fa[maxn];

int rand_a, rand_b, rand_p;

void insert(int u, int v)
{
	e[cnt] = (edge) {v, head[u]}, head[u] = cnt++;
}

int dfs(int u)
{
	int hash = rand_a;

	vector<int> h;

	for (int i = head[u]; i != -1; i = e[i].next)
		h.push_back(dfs(e[i].v));
	sort(h.begin(), h.end());

	for (int i = 0; i < h.size(); i++)
		hash = ((hash * rand_p ) ^ h[i]) % P;
	
	return hash * rand_b % P;
}

void init()
{
	rand_a = rand() % 19000 + 1;
	rand_b = rand() % 19000 + 1;
	rand_p = rand() % 19000 + 1;
}

int solve(char* s)
{
	int n = strlen(s), t = 1;

	cnt = 0, sum = 1;
	memset(head, -1, sizeof head);

	for (int i = 0; i < n; i++) {
		if (s[i] == '0') {
			insert(t, ++sum);
			fa[sum] = t, t = sum;
		}
		if (s[i] == '1')
			t = fa[t];
	}

	return dfs(1);
}

int main()
{
	T = read(), init();

	while (T--) {
		scanf("%s%s", s, t);
		int fs = solve(s);
		int ft = solve(t);

		if (fs == ft)
			printf("same\n");
		else
			printf("different\n");
	}

	return 0;
}

你可能感兴趣的:(POJ1635【树的同构】【hash】)