码迷,mamicode.com
首页 > 其他好文 > 详细

实例分析Robots.txt写法

时间:2014-05-24 18:34:00      阅读:344      评论:0      收藏:0      [点我收藏+]

标签:style   class   blog   c   code   ext   

题意:经典八数码问题

思路:HASH+BFS

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 500000;
const int size = 1000003;
typedef int State[9];

char str[30];
int state[9],goal[9]={1, 2, 3, 4, 5, 6, 7, 8, 0};
int dir[4][2]={{-1,0}, {1,0}, {0,-1}, {0,1}};
char path_dir[5]="udlr";
int st[MAXN][9],fa[MAXN],path[MAXN];
int head[size],next[MAXN];

int hash(State &s) {
	int v = 0;
	for (int i = 0; i < 9; i++)
		v = v*10 + s[i];
	return v % size;
}

int insert(int s) {
	int h = hash(st[s]);
	int u = head[h];
	while (u) {
		if (memcmp(st[u], st[s], sizeof(st[s])) == 0)
			return 0;
		u = next[u];
	}
	next[s] = head[h];
	head[h] = s;
	return 1;
}

int bfs() {
	memset(head, 0, sizeof(head));
	fa[0] = path[0] = -1;
	int front=0,rear=1;
	memcpy(st[0], state, sizeof(state));
	while (front < rear) {
		int *s = st[front];
		if (memcmp(s, goal, sizeof(goal)) == 0)
			return front;
		int cnt;
		for (cnt = 0; cnt < 9; cnt++) 
			if (s[cnt] == 0)
				break;
		int x = cnt/3, y = cnt%3;
		for (int i = 0; i < 4; i++) {
			int nx = x + dir[i][0];
			int ny = y + dir[i][1];
			int pos = nx*3+ny;
			if (nx >= 0 && nx < 3 && ny >= 0 && ny < 3) {
				int *ns = st[rear];
				memcpy(ns, s, sizeof(int)*9);
				ns[cnt] = s[pos];
				ns[pos] = 0;
				if (insert(rear)) {
					fa[rear] = front;
					path[rear] = i;
					rear++;
				}
			}
		}
		front++;
	}
	return -1;
}

void print(int u) {
	if (u) {
		print(fa[u]);
		printf("%c", path_dir[path[u]]);
	}
}

int main() {
	while (gets(str)) {
		int pos = 0;
		for (int i = 0; i < strlen(str); i++) {
			if (str[i] >= '0' && str[i] <= '9')
				state[pos++] = str[i] - '0';
			else if (str[i] == 'x')
				state[pos++] = 0;
		}
		int ans = bfs();
		if (ans != -1) {
			print(ans);
			printf("\n");
		}
	}
	return 0;	
}



实例分析Robots.txt写法,布布扣,bubuko.com

实例分析Robots.txt写法

标签:style   class   blog   c   code   ext   

原文地址:http://blog.csdn.net/seowhat/article/details/26582721

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!