Example #1
0
double dfs(state &u) {
	if (u.c.size() == 1)	return 0;
	sort(u.c.begin() + 1, u.c.end());
	int h = u.hash();
	if (hash[h].find(u) != hash[h].end())
		return hash[h][u];
	double &ret = hash[h][u];
	double self = 0, total = 0;
	ret = 0;
	for (int i = 0; i < u.c.size(); i++)
		total += u.c[i];
	total = total - 1, self = u.c[0] - 1;
	for (int i = 1; i < u.c.size(); i++) {
		state v = u;
		v.c[0] += v.c[i];
		v.c.erase(v.c.begin() + i);
		ret += u.c[i] * dfs(v);
	}
	// E[u] = 1 + E[v] * p + E[u] * q
	ret = (ret / total) + 1;
	ret = ret / (1 - self / total);
	return ret;
}
Example #2
0
int bfs(state init) {
	for (int i = 0; i < hash_mod; i++)
		hash[i].clear();
	int h = init.hash(), ti, tj;
	state u, v;
	queue<state> Q;
	Q.push(init), hash[h][init] = 0;
	while (!Q.empty()) {
		u = Q.front(), Q.pop();
		h = u.hash();
		int step = hash[h][u];
		if (u.g[2][4] == 'w' && u.g[2][5] == 'w') {
//			u.print();
			return step;
		}
		for (int i = 0; i < 6; i++) {
			for (int j = 0; j < 6; j++) {
				if (u.g[i][j] < 'a' || u.g[i][j] > 'z')
					continue;
				ti = i, tj = j;
				v = u;
				while (ti-1 >= 0 && v.g[ti-1][tj] == ' ' && ti+1 < 6 && v.g[ti][tj] == v.g[ti+1][tj]) { // shift up
					v = shiftup(v, ti, tj);
					ti--;
					h = v.hash();
					if (hash[h].find(v) == hash[h].end()) {
						hash[h][v] = step+1;
						Q.push(v);
					}
//					v.print();
				}
				ti = i, tj = j;
				v = u;
				while (ti-1 >= 0 && v.g[ti-1][tj] == v.g[ti][tj] && ti+1 < 6 && v.g[ti+1][tj] == ' ') { // shift down
					v = shiftdown(v, ti, tj);
					ti++;
					h = v.hash();
					if (hash[h].find(v) == hash[h].end()) {
						hash[h][v] = step+1;
						Q.push(v);
					}
//					v.print();
				}
				ti = i, tj = j;
				v = u;
				while (tj-1 >= 0 && v.g[ti][tj-1] == ' ' && tj+1 < 6 && v.g[ti][tj] == v.g[ti][tj+1]) { // shift left
					v = shiftleft(v, ti, tj);
					tj--;
					h = v.hash();
					if (hash[h].find(v) == hash[h].end()) {
						hash[h][v] = step+1;
						Q.push(v);
					}
//					v.print();
				}
				ti = i, tj = j;
				v = u;
				while (tj-1 >= 0 && v.g[ti][tj-1] == v.g[ti][tj] && tj+1 < 6 && v.g[ti][tj+1] == ' ') { // shift right
					v = shiftright(v, ti, tj);
					tj++;
					h = v.hash();
					if (hash[h].find(v) == hash[h].end()) {
						hash[h][v] = step+1;
						Q.push(v);
					}
//					v.print();
				}
			}
		}
	}
	return -1;
}