习题7-2 黄金图形(Golygons, ACM/ICPC World Finals 1993, UVa225)

唯一需要注意的就是每个点只经过一次。回溯法求解即可。

我写的好像有点慢,把不能过的点存数组应该能快些。1.03s

#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <algorithm>
#include <sstream>
#include <utility>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <cctype>
#define CLEAR(a, b) memset(a, b, sizeof(a))
#define IN() freopen("in.txt", "r", stdin)
#define OUT() freopen("out.txt", "w", stdout)
#define LL long long
#define mod 1000000007
#define INF 1000000007
#define eps 1e-5
#define PI 3.1415926535898
using namespace std;
//-------------------------CHC------------------------------//
const int maxn = 25;
const char dircs[] = "ensw";
const int dx[] = { 0, 1, -1, 0 };
const int dy[] = { 1, 0, 0, -1 };
const int walk[4][2] = { 1, 2, 0, 3, 0, 3, 1, 2 };
int n, k, cnt;
char ans[maxn];
pair<int, int> points[10005], cities[10005];
int fp, fc;

bool inside(int x, int y, int x1, int y1, int x2, int y2) {
	if ((x - x1)*(y - y2) + (x - x2) * (y - y1) != 0) return false;
	if ((x - x2)*(x - x1) > 0 || (y - y1) * (y - y2) > 0) return false;
	return true;
}

bool check(int x1, int y1, int x2, int y2) {
	for (int i = 0; i < fc; ++i)
		if (x1 == cities[i].first && y1 == cities[i].second)
			return false;
	for (int i = 0; i < fp; ++i) {
		int x = points[i].first, y = points[i].second;
		if (inside(x, y, x1, y1, x2, y2)) return false;
	}
	return true;
}

void dfs(int x, int y, int dir, int d) {
	int nx = x + dx[dir] * d, ny = y + dy[dir] * d;
	//printf("x = %d, y = %d\n", nx, ny);
	if (!check(nx, ny, x, y)) return;
	if (d == n) {
		if (nx == 0 && ny == 0) {
			++cnt;
			for (int i = 0; i < n; ++i)
				putchar(ans[i]);
			puts("");
		}
		return;
	}
	for (int i = 0; i < 2; ++i) {
		int ndir = walk[dir][i];
		ans[d] = dircs[ndir];
		cities[fc++] = make_pair(nx, ny);
		dfs(nx, ny, ndir, d + 1);
		fc--;
	}
}

int main() {
	//IN(); OUT();
	int t;
	scanf("%d", &t);
	while (t--) {
		fp = fc = 0;
		scanf("%d%d", &n, &k);
		while (k--) {
			int x, y;
			scanf("%d%d", &y, &x);
			points[fp++] = make_pair(x, y);
		}
		cnt = 0;
		for (int i = 0; i < 4; ++i) {
			ans[0] = dircs[i];
			dfs(0, 0, i, 1);
		}
		printf("Found %d golygon(s).\n\n", cnt);
	}
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值