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

UVA - 225 Golygons

时间:2014-07-09 12:23:55      阅读:421      评论:0      收藏:0      [点我收藏+]

标签:style   os   for   io   amp   size   

题意:求从原点开始依次走1,2...n步后到回到原点的方案数,其中不能经过障碍,每次必须左右拐

思路:一个比较简单的DFS,结果做了好久

#include <iostream>
#include <cstring>
#include <algorithm>
#include <cstdio>
using namespace std;

const int MAXN = 250;
const int Add = 100;

int n, ans;
int G[MAXN][MAXN], step[MAXN], sum[MAXN];
int dx[4]={1, 0, 0, -1};
int dy[4]={0, 1, -1, 0};
char sign[5]="ensw";

bool check(int x, int y, int d, int k) {
	for (int i = 1; i <= k; i++) {
		x += dx[d];
		y += dy[d];
		if (abs(x) > Add || abs(y) > Add)
			continue;
		if (G[x+Add][y+Add] == -1)
			return true;
	}
	if (abs(x)+abs(y) > sum[20] - sum[k])
		return true;
	return false;
}

void dfs(int x, int y, int cnt, int last) {
	if (cnt > n) {
		if (x == 0 && y == 0) {
			for (int i = 1; i <= n; i++)
				printf("%c", sign[step[i]]);
			printf("\n");
			ans++;
		}
		return;
	}
	int &i = step[cnt];
	for (i = 0; i < 4; i++) {
		if (i == last || i+last == 3)
			continue;
		if (check(x, y, i, cnt))
			continue;
		int nx = x + dx[i]*cnt;
		int ny = y + dy[i]*cnt;
		if (G[nx+Add][ny+Add])
			continue;
		G[nx+Add][ny+Add] = 1;
		dfs(nx, ny, cnt+1, i);
		G[nx+Add][ny+Add] = 0;
	}
}

int main() {
	sum[0] = 0;
	for (int i = 1; i <= 20; i++)	
		sum[i] = sum[i-1] + i;
	int t, k;
	scanf("%d", &t);
	while (t--) {
		scanf("%d%d", &n, &k);
		memset(G, 0, sizeof(G));
		ans = 0;
		for (int i = 0; i < k; i++) {
			int a, b;
			scanf("%d%d", &a, &b);
			if (abs(a) > Add || abs(b) > Add)
				continue;
			G[a+Add][b+Add] = -1;
		}
		dfs(0, 0, 1, -1);
		printf("Found %d golygon(s).\n\n", ans);
	}
	return 0;
}



UVA - 225 Golygons,布布扣,bubuko.com

UVA - 225 Golygons

标签:style   os   for   io   amp   size   

原文地址:http://blog.csdn.net/u011345136/article/details/37572529

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