hdu 5612 Baby Ming and Matrix games
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了hdu 5612 Baby Ming and Matrix games相关的知识,希望对你有一定的参考价值。
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5612
题意:给出一个矩阵,在(i*2,j*2)(i,j = 0, 1, 2...)是数字0-9,数字之间是+,-,*,/运算符。其他位置是#号。
问给出一个数字,有没有可能在矩阵中找到一条路线可以计算得到这个数字。
思路:DFS搜索
1 #include <bits/stdc++.h> 2 using namespace std; 3 char mp[35][35]; 4 int T; 5 int vis[35][35]; 6 int n, m; 7 double sum; 8 #define eps 1e-10 9 bool flag; 10 void dfs(int x, int y, double val) 11 { 12 if(flag) return; 13 if(fabs(sum-val) < eps) 14 { 15 flag = true; return; 16 } 17 if(x-2 >= 0) 18 { 19 if(!vis[x-2][y]) 20 { 21 vis[x-2][y] = 1; 22 if(mp[x-1][y] == ‘*‘) dfs(x-2, y, val*(mp[x-2][y]-‘0‘)); 23 else if(mp[x-1][y] == ‘+‘) dfs(x-2, y, val+(mp[x-2][y]-‘0‘)); 24 else if(mp[x-1][y] == ‘-‘) dfs(x-2, y, val-(mp[x-2][y]-‘0‘)); 25 else if(mp[x-1][y] == ‘/‘) dfs(x-2, y, val/(mp[x-2][y]-‘0‘)); 26 vis[x-2][y] = 0; 27 } 28 } 29 if(x+2 <= n-1) 30 { 31 if(!vis[x+2][y]) 32 { 33 vis[x+2][y] = 1; 34 if(mp[x+1][y] == ‘*‘) dfs(x+2, y, val*(mp[x+2][y]-‘0‘)); 35 else if(mp[x+1][y] == ‘+‘) dfs(x+2, y, val+(mp[x+2][y]-‘0‘)); 36 else if(mp[x+1][y] == ‘-‘) dfs(x+2, y, val-(mp[x+2][y]-‘0‘)); 37 else if(mp[x+1][y] == ‘/‘) dfs(x+2, y, val/(mp[x+2][y]-‘0‘)); 38 vis[x+2][y] = 0; 39 40 } 41 } 42 if(y-2 >= 0) 43 { 44 if(!vis[x][y-2]) 45 { 46 vis[x][y-2] = 1; 47 if(mp[x][y-1] == ‘*‘) dfs(x, y-2, val*(mp[x][y-2]-‘0‘)); 48 else if(mp[x][y-1] == ‘+‘) dfs(x, y-2, val+(mp[x][y-2]-‘0‘)); 49 else if(mp[x][y-1] == ‘-‘) dfs(x, y-2, val-(mp[x][y-2]-‘0‘)); 50 else if(mp[x][y-1] == ‘/‘) dfs(x, y-2, val/(mp[x][y-2]-‘0‘)); 51 vis[x][y-2] = 0; 52 } 53 } 54 55 if(y+2 <= m-1) 56 { 57 if(!vis[x][y+2]) 58 { 59 vis[x][y+2] = 1; 60 if(mp[x][y+1] == ‘*‘) dfs(x, y+2, val*(mp[x][y+2]-‘0‘)); 61 else if(mp[x][y+1] == ‘+‘) dfs(x, y+2, val+(mp[x][y+2]-‘0‘)); 62 else if(mp[x][y+1] == ‘-‘) dfs(x, y+2, val-(mp[x][y+2]-‘0‘)); 63 else if(mp[x][y+1] == ‘/‘) dfs(x, y+2, val/(mp[x][y+2]-‘0‘)); 64 vis[x][y+2] = 0; 65 } 66 } 67 68 return; 69 70 } 71 int main() 72 { 73 scanf("%d", &T); 74 while(T--) 75 { 76 scanf("%d%d%lf", &n, &m, &sum); 77 for(int i = 0; i < n; i++) 78 { 79 scanf("%s", mp[i]); 80 } 81 82 flag = false; 83 for(int i = 0; i < n; i+=2) 84 { 85 for(int j = 0; j < m; j+=2) 86 { 87 memset(vis, 0, sizeof(vis)); 88 vis[i][j] = 1; 89 dfs(i, j, mp[i][j]-‘0‘); 90 if(flag == true) break; 91 } 92 if(flag == true) break; 93 } 94 if(flag) printf("Possible\n"); 95 else printf("Impossible\n"); 96 } 97 return 0; 98 }
以上是关于hdu 5612 Baby Ming and Matrix games的主要内容,如果未能解决你的问题,请参考以下文章
hdu5612 Baby Ming and Matrix games (dfs加暴力)
HDU 5610 Baby Ming and Weight lifting 暴力
HDU 5611 Baby Ming and phone number
BestCoder Round #69 (div.2) Baby Ming and Weight lifting(hdu 5610)