UVa 439/HDU 1372/POJ 2243/ZOJ 1091 Knight Moves(BFS纯数学方法)

2024-03-05 21:08

本文主要是介绍UVa 439/HDU 1372/POJ 2243/ZOJ 1091 Knight Moves(BFS纯数学方法),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

439 - Knight Moves

Time limit: 3.000 seconds

http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=105&page=show_problem&problem=380

http://acm.hdu.edu.cn/showproblem.php?pid=1372

http://poj.org/problem?id=2243

http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1091

A friend of you is doing research on the Traveling Knight Problem (TKP) where you are to find the shortest closed tour of knight moves that visits each square of a given set of n squares on a chessboard exactly once. He thinks that the most difficult part of the problem is determining the smallest number of knight moves between two given squares and that, once you have accomplished this, finding the tour would be easy.

Of course you know that it is vice versa. So you offer him to write a program that solves the "difficult" part.

Your job is to write a program that takes two squares a and b as input and then determines the number of knight moves on a shortest route from a to b.

Input Specification

The input file will contain one or more test cases. Each test case consists of one line containing two squares separated by one space. A square is a string consisting of a letter (a-h) representing the column and a digit (1-8) representing the row on the chessboard.

Output Specification

For each test case, print one line saying "To get from xx to yy takes n knight moves.".

Sample Input

e2 e4
a1 b2
b2 c3
a1 h8
a1 h7
h8 a1
b1 c3
f6 f6

Sample Output

To get from e2 to e4 takes 2 knight moves.
To get from a1 to b2 takes 4 knight moves.
To get from b2 to c3 takes 2 knight moves.
To get from a1 to h8 takes 6 knight moves.
To get from a1 to h7 takes 5 knight moves.
To get from h8 to a1 takes 6 knight moves.
To get from b1 to c3 takes 1 knight moves.
To get from f6 to f6 takes 0 knight moves.

题意:

在辽阔的N*N大草原上(棋盘)上你有一只草泥马,马走日。求从a到b怎么走步数最小。


思路:

1. BFS,复杂度O(N^2),N指棋盘边长。

2. 数学方法,复杂度O(N^2),但系数比第一种小很多:

设横纵坐标的差值分别是x,y。由于我们的草泥马只能有8种走法,实际上只会出现4种(方向向量有(1,2),(2,1),(1,-2),(2,-1),(-1,2),(-2,1),(-1,-2),(-2,-1)8种,但是如果要走最小的次数,就不可能同时出现(1,2)和(-1,-2)这样相反的方向向量,所以只会出现4种)。所以,我们设方向向量为(1,2),(2,1),(2,-1),(1,-2)的有a,b,c,d次,其中a,b,c,d可以为负数(比如a为负数代表方向向量为(-1,-2))。

于是,可以列两个方程:


我们要求的是|a|+|b|+|c|+|d|的最小值。把a,b,看做常量,解得:


所以a+2b≡2x+y(mod 3),即a≡-2b+2x+y(mod 3)(-3≤a,b3)

但由于a,b关系的制约,当b在-3到3范围内变动时,a只有三种情况(取-3,0,3或-2,1或-1,2)

所以a,b的组合有16或17种,比较每种情况的|a|+|b|+|c|+|d|,求最小的即可。

但是在计算角落时要另外考虑,比如(a1,b2)按上面方法算的是2,实际是4。

经过计算知,对于8*8的只有4种情况:(a1,b2),(a8,b7),(g2,h1),(g7,h8),

对这四种情况单独拿出来说就好了。


完整代码:

BFS,很慢。

/*UVaOJ: 0.022s*/
/*HDU: 31ms,244KB*/
/*POJ: 266ms,156KB*/
/*ZOJ: 10ms,180KB*/#include<cstdio>
#include<queue>
#include<cstring>
using namespace std;bool vis[9][9];
int a, b, c, d;
int mov[8][2] = {1, 2, -1, 2, -2, 1, -2, -1, -1, -2, 1, -2, 2, -1, 2, 1};struct node
{int x, y, step;
} lnode;int bfs()
{int i;queue<node>q;node cur, next;cur.x = a;cur.y = b;cur.step = 0;vis[cur.x][cur.y] = true;q.push(cur);while (!q.empty()){cur = q.front();q.pop();for (i = 0; i < 8; i++){next.x = cur.x + mov[i][0];next.y = cur.y + mov[i][1];if (next.x >= 1 && next.x <= 8 && next.y >= 1 && next.y <= 8){if (next.x == c && next.y == d){next.step = cur.step + 1;return next.step;}if (!vis[next.x][next.y]){next.step = cur.step + 1;vis[next.x][next.y] = true;q.push(next);}}}}return -1;
}int main()
{char str[5], str2[5];while (~scanf("%s %s", str, str2)){memset(vis, 0, sizeof(vis));a = str[0] - '`' ;//'a'前面是'`'b = str[1] - '0';c = str2[0] - '`' ;d = str2[1] - '0';int ans = 0;if (a != c || b != d)ans = bfs();printf("To get from %s to %s takes %d knight moves.\n", str, str2, ans);}return 0;
}


数学方法,较快。

/*UVaOJ: 0.019s*/
/*HDU: 15ms,232KB*/
/*POJ: 16ms,144KB*/
/*ZOJ: 0ms,180KB*/#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;int main()
{char except[8][3] = {"a1", "b2", "a8", "b7", "g2", "h1", "g7", "h8"};char s1[5], s2[5];int  x, y, a, b, c, d,sum, m, temp;while (~scanf("%s%s", s1, s2)){if (!strcmp(s1, s2)){printf("To get from %s to %s takes 0 knight moves.\n", s1, s2);continue;}bool flag = false;for (int i = 0; i < 8; i += 2)if (!((strcmp(s1, except[i]) || strcmp(s2, except[i + 1]))&& (strcmp(s1, except[i + 1]) || strcmp(s2, except[i])))){flag = true;break;}if (flag){printf("To get from %s to %s takes 4 knight moves.\n", s1, s2);continue;}x = s2[0] - s1[0];y = s2[1] - s1[1];sum = 1 << 6;//下面a,b的取值范围是由-3<=a,b<=3所确定的//注意b取负数和正数的情况是不一样的//注意取模时,-1%3!=2而是=-1for (b = -3; b <= 3; b++){m = (y + 2 * x - 2 * b) % 3;for (a = m - 3; a <= m + 3; a += 3){c = (2 * x + y - 4 * a - 5 * b) / 3;d = (5 * a + 4 * b - x - 2 * y) / 3;temp = abs(a) + abs(b) + abs(c) + abs(d);if (temp < sum)sum = temp;}}printf("To get from %s to %s takes %d knight moves.\n", s1, s2, sum);}return 0;
}


题外话:可以打表。

这篇关于UVa 439/HDU 1372/POJ 2243/ZOJ 1091 Knight Moves(BFS纯数学方法)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/777809

相关文章

hdu1254(嵌套bfs,两次bfs)

/*第一次做这种题感觉很有压力,思路还是有点混乱,总是wa,改了好多次才ac的思路:把箱子的移动当做第一层bfs,队列节点要用到当前箱子坐标(x,y),走的次数step,当前人的weizhi(man_x,man_y),要判断人能否将箱子推到某点时要嵌套第二层bfs(人的移动);代码如下:

【C++】_list常用方法解析及模拟实现

相信自己的力量,只要对自己始终保持信心,尽自己最大努力去完成任何事,就算事情最终结果是失败了,努力了也不留遗憾。💓💓💓 目录   ✨说在前面 🍋知识点一:什么是list? •🌰1.list的定义 •🌰2.list的基本特性 •🌰3.常用接口介绍 🍋知识点二:list常用接口 •🌰1.默认成员函数 🔥构造函数(⭐) 🔥析构函数 •🌰2.list对象

usaco 1.3 Mixing Milk (结构体排序 qsort) and hdu 2020(sort)

到了这题学会了结构体排序 于是回去修改了 1.2 milking cows 的算法~ 结构体排序核心: 1.结构体定义 struct Milk{int price;int milks;}milk[5000]; 2.自定义的比较函数,若返回值为正,qsort 函数判定a>b ;为负,a<b;为0,a==b; int milkcmp(const void *va,c

浅谈主机加固,六种有效的主机加固方法

在数字化时代,数据的价值不言而喻,但随之而来的安全威胁也日益严峻。从勒索病毒到内部泄露,企业的数据安全面临着前所未有的挑战。为了应对这些挑战,一种全新的主机加固解决方案应运而生。 MCK主机加固解决方案,采用先进的安全容器中间件技术,构建起一套内核级的纵深立体防护体系。这一体系突破了传统安全防护的局限,即使在管理员权限被恶意利用的情况下,也能确保服务器的安全稳定运行。 普适主机加固措施:

webm怎么转换成mp4?这几种方法超多人在用!

webm怎么转换成mp4?WebM作为一种新兴的视频编码格式,近年来逐渐进入大众视野,其背后承载着诸多优势,但同时也伴随着不容忽视的局限性,首要挑战在于其兼容性边界,尽管WebM已广泛适应于众多网站与软件平台,但在特定应用环境或老旧设备上,其兼容难题依旧凸显,为用户体验带来不便,再者,WebM格式的非普适性也体现在编辑流程上,由于它并非行业内的通用标准,编辑过程中可能会遭遇格式不兼容的障碍,导致操

poj 3974 and hdu 3068 最长回文串的O(n)解法(Manacher算法)

求一段字符串中的最长回文串。 因为数据量比较大,用原来的O(n^2)会爆。 小白上的O(n^2)解法代码:TLE啦~ #include<stdio.h>#include<string.h>const int Maxn = 1000000;char s[Maxn];int main(){char e[] = {"END"};while(scanf("%s", s) != EO

uva 10055 uva 10071 uva 10300(水题两三道)

情歌两三首,水题两三道。 好久没敲代码了为暑假大作战热热身。 uva 10055 Hashmat the Brave Warrior 求俩数相减。 两个debug的地方,一个是longlong,一个是输入顺序。 代码: #include<stdio.h>int main(){long long a, b;//debugwhile(scanf("%lld%lld", &

hdu 2093 考试排名(sscanf)

模拟题。 直接从教程里拉解析。 因为表格里的数据格式不统一。有时候有"()",有时候又没有。而它也不会给我们提示。 这种情况下,就只能它它们统一看作字符串来处理了。现在就请出我们的主角sscanf()! sscanf 语法: #include int sscanf( const char *buffer, const char *format, ... ); 函数sscanf()和

hdu 2602 and poj 3624(01背包)

01背包的模板题。 hdu2602代码: #include<stdio.h>#include<string.h>const int MaxN = 1001;int max(int a, int b){return a > b ? a : b;}int w[MaxN];int v[MaxN];int dp[MaxN];int main(){int T;int N, V;s

poj 1511 Invitation Cards(spfa最短路)

题意是给你点与点之间的距离,求来回到点1的最短路中的边权和。 因为边很大,不能用原来的dijkstra什么的,所以用spfa来做。并且注意要用long long int 来存储。 稍微改了一下学长的模板。 stack stl 实现代码: #include<stdio.h>#include<stack>using namespace std;const int M