 patrickcty 2月 20, 2017

那些严重拖慢做题进度的题以及遇到的坑3

1045 Fire Net

Suppose that we have a square city with straight streets. A map of a city is a square board with n rows and n columns, each representing a street or a piece of wall.

A blockhouse is a small castle that has four openings through which to shoot. The four openings are facing North, East, South, and West, respectively. There will be one machine gun shooting through each opening.

Here we assume that a bullet is so powerful that it can run across any distance and destroy a blockhouse on its way. On the other hand, a wall is so strongly built that can stop the bullets.

The goal is to place as many blockhouses in a city as possible so that no two can destroy each other. A configuration of blockhouses is legal provided that no two blockhouses are on the same horizontal row or vertical column in a map unless there is at least one wall separating them. In this problem we will consider small square cities (at most 4x4) that contain walls through which bullets cannot run through.

The following image shows five pictures of the same board. The first picture is the empty board, the second and third pictures show legal configurations, and the fourth and fifth pictures show illegal configurations. For this board, the maximum number of blockhouses in a legal configuration is 5; the second picture shows one way to do it, but there are several other ways.

Your task is to write a program that, given a description of a map, calculates the maximum number of blockhouses that can be placed in the city in a legal configuration.

#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<cstring>
#include <algorithm>

using namespace std;

const int maxn = 10005;

char a;
// visit数组，表示每一格的状态，0为空位置，1为碉堡，2为墙
// 实际上用a数组也可以，不过这里用的是整型数组
int visit;
// 设置为全局变量，便于函数中直接调用
int mmax, cnt;
int n;

// 判断从(i, j)出发向上下左右是否会遇到碉堡
// 也就是是否能在该店放置碉堡
bool ffind(int i, int j)
{
for (int k = j; k <= n; ++k)
{
if (visit[i][k] == 2)
break;
if (visit[i][k] == 1)
return false;
}
for (int k = j; k > 0; --k)
{
// 是visit而不是a
// 所以两个都用的坏处就是容易搞混
if (visit[i][k] == 2)
break;
if (visit[i][k] == 1)
return false;
}
for (int k = i; k <= n; ++k)
{
if (visit[k][j] == 2)
break;
if (visit[k][j] == 1)
return false;
}
for (int k = i; k > 0; --k)
{
// 横纵坐标不要搞错
if (visit[k][j] == 2)
break;
if (visit[k][j] == 1)
return false;
}
return true;
}

// 深度搜索
void dfs()
{
// 每次都保存最大的状态
if (cnt > mmax)
mmax = cnt;
for (int i = 1; i <= n; ++i)
{
for (int j = 1; j <= n; ++j)
{
// 没有放置碉堡并且可以放置碉堡
if (!visit[i][j] && ffind(i, j))
{
visit[i][j] = 1;
cnt++;
dfs();
// 整个搜索完了之后就状态回退
// 便于下一个点出发进行深度搜索
visit[i][j] = 0;
cnt--;
}
}
}
}

int main()
{

while (scanf("%d", &n) && n != 0)
{
for (int i = 1; i <= n; ++i)
{
getchar();
for (int j = 1; j <= n; ++j)
{
scanf("%c", &a[i][j]);
if (a[i][j] == 'X')
visit[i][j] = 2;
else
visit[i][j] = 0;
}
}

cnt = mmax = 0;
dfs();
printf("%d\n", mmax);
}
return 0;
}