标签:
http://acm.hdu.edu.cn/showproblem.php?pid=1045
这是在贪心分类里面的题目,然而我第一眼看到时候还是想到了dfs,毕竟只有4*4……数据小,枚举也能AC
用DFS枚举所有状态……
#include <iostream> #include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <cmath> #include <time.h> #include <string> #include <map> #include <stack> #include <vector> #include <set> #include <queue> #define M 10000 #define maxn (4 + 2) #define pi acos(-1.0) using namespace std; char a[maxn][maxn]; int n,maxs = -1; void Shoot(int t) //假如a[t/n][t%n]放上机枪,那么把它能扫射的区域标记为‘D‘(Die),机枪的位置标记为‘!‘; { int x = t / n; int y = t % n; a[x][y] = ‘!‘; for(int i = x + 1; i < n; i ++) { if(a[i][y] == ‘.‘) a[i][y] = ‘D‘; else if(a[i][y] == ‘X‘) break; else if(a[i][y] != ‘!‘) a[i][y] ++; } for(int i = x - 1; i >= 0; i --) { if(a[i][y] == ‘.‘) a[i][y] = ‘D‘; else if(a[i][y] == ‘X‘) break; else if(a[i][y] != ‘!‘) a[i][y] ++; } for(int i = y + 1; i < n; i ++) { if(a[x][i] == ‘.‘) a[x][i] = ‘D‘; else if(a[x][i] == ‘X‘) break; else if(a[x][i] != ‘!‘) a[x][i] ++; } for(int i = y - 1; i >= 0; i --) { if(a[x][i] == ‘.‘) a[x][i] = ‘D‘; else if(a[x][i] == ‘X‘) break; else if(a[x][i] != ‘!‘) a[x][i] ++; } } void Live(int t) //假如a[t/n][t%n]不放机枪,那么逆转上面的函数; { int x = t / n; int y = t % n; a[x][y] = ‘.‘; for(int i = x + 1; i < n; i ++) { if(a[i][y] == ‘X‘) break; else if(a[i][y] == ‘D‘) a[i][y] = ‘.‘; else if(a[i][y] == ‘E‘) a[i][y] = ‘D‘; } for(int i = x - 1; i >= 0; i --) { if(a[i][y] == ‘X‘) break; else if(a[i][y] == ‘D‘) a[i][y] = ‘.‘; else if(a[i][y] == ‘E‘) a[i][y] = ‘D‘; } for(int i = y + 1; i < n; i ++) { if(a[x][i] == ‘X‘) break; else if(a[x][i] == ‘D‘) a[x][i] = ‘.‘; else if(a[x][i] == ‘E‘) a[x][i] = ‘D‘; } for(int i = y - 1; i >= 0; i --) { if(a[x][i] == ‘X‘) break; else if(a[x][i] == ‘D‘) a[x][i] = ‘.‘; else if(a[x][i] == ‘E‘) a[x][i] = ‘D‘; } } void Dfs(int t) //用DFS搜索, { if(t >= n * n) //到达分支的结尾时候,查找一共有多少机枪 { int cnt = 0; for(int i = 0; i < n; i ++) for(int j = 0; j < n; j ++) if(a[i][j] == ‘!‘) cnt ++; maxs = max(maxs,cnt); return; } if(a[t / n][t % n] != ‘.‘) Dfs(t + 1); //如果这个位置不能放机枪,就到下一位置 else { Shoot(t); //此地放上机枪 Dfs(t + 1); Live(t); //此地不放机枪 Dfs(t + 1); } } int main() { // freopen("in.txt","r",stdin); // freopen("out.txt","w",stdout); while(scanf("%d",&n) && n) { maxs = -1; for(int i = 0; i < n; i ++) scanf("%s",a[i]); Dfs(0); printf("%d\n",maxs); } return 0; }
标签:
原文地址:http://www.cnblogs.com/zouqihan/p/5003026.html