ZOJ-1264

来源:互联网 发布:rds 慢sql 编辑:程序博客网 时间:2024/06/03 16:34

效率要求比较高的搜索,搞了我一个晚上。。试了N种优化的办法最后总算A了,小有成就感,哈哈。核心就是DFS没什么好说的,关键是剪枝优化,开始我一直用vector存的源数据,这种情况下去换了N种方法优化还是TLE,包括先放四个角,记录状态啊什么的,统统没用。。后来试着用map去存源数据,这种重复的块就不用存两遍,map的value增加就行了,因此块的总数减少了,就能大大缩减搜索时间,这样就可以A了!上代码

#include<iostream>#include<string>#include<cstring>#include<map>using namespace std;namespace{int n, m;string p[6][6];bool can;map<string, int> M;char match(char c){if (c == 'I')return 'O';else if (c == 'O')return 'I';elsereturn 'F';}void dfs(int depth){if (can)return;if (depth == n * m){can = true;return;}int r = depth / m, c = depth % m;char ch[4];memset(ch, 0, sizeof(ch));ch[0] = r ? match(p[r - 1][c][2]) : 'F';ch[3] = c ? match(p[r][c - 1][1]) : 'F';if (r + 1 == n)ch[2] = 'F';if (c + 1 == m)ch[1] = 'F';for (map<string, int>::iterator it = M.begin(); it != M.end(); it++){if ((*it).second == 0)continue;bool put = true;string now = (*it).first;for (int j = 0; j < 4; j++)if ((ch[j] && ch[j] != now[j]) || ((!ch[j]) && (now[j] == 'F'))){put = false;break;}if (put){(*it).second--;p[r][c] = now;dfs(depth + 1);(*it).second++;}}}bool precheck(){int I[4], O[4], F[4];memset(I, 0, sizeof(I));memset(O, 0, sizeof(O));memset(F, 0, sizeof(F));for (map<string, int>::iterator it = M.begin(); it != M.end(); it++)for (int i = 0; i < (*it).second; i++)for (size_t j = 0; j < 4; j++){if ((*it).first[j] == 'I')I[j]++;else if ((*it).first[j] == 'O')O[j]++;elseF[j]++;}return I[0] == O[2] && O[0] == I[2] && I[1] == O[3] && I[3] == O[1]&& F[0] == F[2] && F[0] == m && F[1] == F[3] && F[1] == n;}}int main(){string s;while (cin >> n >> m, n || m){M.clear();for (int i = 0; i < n * m; i++){cin >> s;if (M.find(s) == M.end())M[s] = 1;elseM[s]++;}can = false;if (precheck())dfs(0);cout << (can ? "YES" : "NO") << endl;}return 0;}


0 0
原创粉丝点击