【USACO2.4.2】穿越栅栏 BFS爆搜

USACO的编译器好恶心,gets不让我编译过……只能getchar了
<pre>Executing...
   Test 1: TEST OK [0.005 secs, 3584 KB]
   Test 2: TEST OK [0.003 secs, 3584 KB]
   Test 3: TEST OK [0.003 secs, 3584 KB]
   Test 4: TEST OK [0.003 secs, 3584 KB]
   Test 5: TEST OK [0.003 secs, 3584 KB]
   Test 6: TEST OK [0.005 secs, 3584 KB]
   Test 7: TEST OK [0.003 secs, 3584 KB]
   Test 8: TEST OK [0.005 secs, 3584 KB]
   Test 9: TEST OK [0.003 secs, 3584 KB]
   Test 10: TEST OK [0.003 secs, 3584 KB]

All tests OK.

 
 
</pre><pre name="code" class="cpp">//[-Waggressive-loop-optimizations]
/*
TASK:maze1
LANG:C++
*/
#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;

int n, m;
int exit_x1 = -1,exit_x2, exit_y1, exit_y2;
char my_map[210][80];
int vis[210][80];

inline void check(int x, int y)
{
	if (my_map[x][y] != ' ')	return;
	if (exit_x1 == -1)
	{
		exit_x1 = x;
		exit_y1 = y;
		return;	
	}
	exit_x2 = x;
	exit_y2 = y;
}


void read(char *s)
{
	char ch;
	int len = 0;
	while ((ch = getchar()) != '\n')
	{
		s[len++] = ch;
	}
}

void init()
{
	scanf("%d%d\n", &n, &m);
	int i;
	for ( i = 0; i <= 2 * m; ++ i)	read(my_map[i]);
	for ( i = 0; i <= 79; ++ i)	my_map[2 * m + 1][i] ='|';
	for ( i = 1; i <= 2 * n - 1;  i += 2)
	{
		check(0, i);
		check(2 * m,i);
	}
	for ( i = 1; i <= 2 * m - 1; i += 2)
	{
		check(i, 0);	
		check(i, 2 * n);
	}
}

const int dx[4] = {0 ,0 , 1, -1};
const int dy[4] = {1, -1, 0, 0};

typedef pair<int, int> PII;
queue<PII>q;
int ans = 0;

void doit()
{
	memset(vis, -1, sizeof(vis));
	q.push(make_pair(exit_x2, exit_y2));
	q.push(make_pair(exit_x1, exit_y1));
	vis[exit_x1][exit_y1] = 1;
	vis[exit_x2][exit_y2] = 1;
	while (!q.empty())
	{
		int now_x = q.front().first;
		int now_y = q.front().second;	
		int t = vis[now_x][now_y];
		q.pop();
		for (int i = 0; i != 4; ++ i)	
		{
			int will_x = now_x + dx[i];
			int will_y = now_y + dy[i];	
			if (will_y > 2 * n)	continue;
			if (will_y < 0)	continue;
			if (my_map[will_x][will_y] == '|' || my_map[will_x][will_y] == '-' || my_map[will_x][will_y] == '+')	continue;

			if (vis[will_x][will_y] == -1)
			{
				vis[will_x][will_y] = t + 1;
				if (ans < t + 1)	ans = t + 1;
				q.push(make_pair(will_x, will_y));
			}
		}
	}
	printf("%d\n", ans/2);
}

int main()
{
//	freopen("maze1.in","r",stdin);
//	freopen("maze1.out","w",stdout);
	init();
	doit();
	return 0;

}

你可能感兴趣的:(【USACO2.4.2】穿越栅栏 BFS爆搜)