Beyond the Void
BYVoid
USACO 5.2.1 Snail Trails 蜗牛的旅行 snail

一道简单的题,模拟蜗牛走的路线,深搜,计算走的最多步数即可。

注意题目中说的“当 N 〉26 时,输入文件就不能表示 Z 列以后的路障了”,这句话不用专门理他。其实就是从A的ascii码开始向后顺延,不管是什么字母就行了。

<pre><span>USER: CmYkRgB123 CmYkRgB123 [cmykrgb1]
TASK: snail
LANG: C++

Compiling...
Compile: OK

Executing...
   Test 1: TEST OK [0.000 secs, 2856 KB]
   Test 2: TEST OK [0.000 secs, 2852 KB]
   Test 3: TEST OK [0.000 secs, 2856 KB]
   Test 4: TEST OK [0.022 secs, 2852 KB]
   Test 5: TEST OK [0.011 secs, 2856 KB]
   Test 6: TEST OK [0.011 secs, 2852 KB]
   Test 7: TEST OK [0.000 secs, 2856 KB]
   Test 8: TEST OK [0.000 secs, 2852 KB]
   Test 9: TEST OK [0.000 secs, 2856 KB]
   Test 10: TEST OK [0.000 secs, 2856 KB]
   Test 11: TEST OK [0.011 secs, 2852 KB]
   Test 12: TEST OK [0.032 secs, 2856 KB]

All tests OK.
</span>
<span>Your program ('snail') produced all correct answers!  This is your
submission #2 for this problem.  <strong>Congratulations!</strong>
</span>
</pre>
/*
ID: cmykrgb1
PROG: snail
LANG: C++
*/

#include <iostream>
#include <fstream>
#define MAX 121

using namespace std;

ifstream fi("snail.in");
ofstream fo("snail.out");

char M[MAX][MAX];
int maxstep=0;
int N,B;

void init()
{
	int i,b;
	char a;
	fi >> N >> B;
	for (i=1;i<=B;i++)
	{
		b=fi.get();
		fi >> a >> b;
		a-='A'-1;
		M[a][b]='#';
	}
}

int max(int a,int b)
{
	return a>b?a:b;
}

void dfs(int x,int y,int step)
{
	int dx,dy;
	bool r;

	for (dx=x+1,dy=y,r=false;dx<=N;dx++) //右
	{
		if (M[dx][dy]=='#')
			break;
		if (M[dx][dy]==1)
		{
			maxstep=max(maxstep,step+dx-x);
			r=true;
			break;
		}
		M[dx][dy]=1;
	}
	dx--;
	if(!r && !(dx==x && dy==y)) dfs(dx,dy,step+dx-x);
	for (;dx>=x+1;dx--)
		M[dx][dy]=0;

	for (dx=x-1,dy=y,r=false;dx>=1;dx--) //左
	{
		if (M[dx][dy]=='#')
			break;
		if (M[dx][dy]==1)
		{
			maxstep=max(maxstep,step+x-dx);
			r=true;
			break;
		}
		M[dx][dy]=1;
	}
	dx++;
	if(!r && !(dx==x && dy==y)) dfs(dx,dy,step+x-dx);
	for (;dx<=x-1;dx++)
		M[dx][dy]=0;

	for (dx=x,dy=y+1,r=false;dy<=N;dy++) //下
	{
		if (M[dx][dy]=='#')
			break;
		if (M[dx][dy]==1)
		{
			maxstep=max(maxstep,step+dy-y);
			r=true;
			break;
		}
		M[dx][dy]=1;
	}
	dy--;
	if(!r && !(dx==x && dy==y)) dfs(dx,dy,step+dy-y);
	for (;dy>=y+1;dy--)
		M[dx][dy]=0;

	for (dx=x,dy=y-1,r=false;dy>=1;dy--) //上
	{
		if (M[dx][dy]=='#')
			break;
		if (M[dx][dy]==1)
		{
			maxstep=max(maxstep,step+y-dy);
			r=true;
			break;
		}
		M[dx][dy]=1;
	}
	dy++;
	if(!r && !(dx==x && dy==y)) dfs(dx,dy,step+y-dy);
	for (;dy<=y-1;dy++)
		M[dx][dy]=0;
}

void print()
{
	fo << maxstep << endl;
	fi.close();
	fo.close();
}

int main()
{
	init();
	M[1][1]=1;
	dfs(1,1,0);
	print();
	return 0;
}

上次修改时间 2017-05-22

相关日志