hdu 5612 Baby Ming and Matrix games
题意: 给一个矩形,两个0~9的数字之间隔一个数学运算符(‘+’,’-‘,’*’,’/’),其中’/’表示分数除,再给一个目标的值,问是否存在从一个数字出发,以数字之间的运算符为运算,得到这个目标值;(每个数字只能用一次,其实说白了就是dfs..);可以则输出(Impossible),否则输出(Possible);
思路:坑点就是里面本来全是整数,但是一个除法运算却是分数形式,开始使用了很保险的分数保存,来避免误差的。但是无情WA了很多次。。突然发现写成了(ImPossible)…醉了,然后以为现在肯定要A了,但是还是WA了。。。(有兴趣的帮我找找bug哈!真心感谢)之后重写了一个double类型的,无奈啊(太水了),下面是A和WA两份代码
#include<iostream> #include<cstdio> #include<cstring> #include<string.h> #include<algorithm> #include<map> #include<queue> #include<vector> #include<cmath> #include<stdlib.h> #include<time.h> using namespace std; #define rep(i,n) for(int i = 1;i <= n;i++) #define MS0(a) memset(a,0,sizeof(a)) #define esp 1e-6 int n,m,vis[35][35],f; double sum; char s[35][35]; int dir[2][4] = {{0,1,0,-1},{1,0,-1,0}}; double cal(double val,double v,char op) { if(op == '+') return val + v; else if(op == '-') return val - v; else if(op == '*') return val * v; return val/v; } void dfs(int i,int j,double val) { if(fabs(val - sum) < esp) f = 0; for(int k = 0;k < 4 && f;k++){ int x = i + 2*dir[0][k] , y = j + 2*dir[1][k]; char op = s[i + dir[0][k]][j + dir[1][k]]; if(x < 1 || x > n || y < 1 || y > m || vis[x][y]) continue; int v = s[x][y] - '0'; if(op == '/' && v == 0) continue; vis[x][y] = 1; dfs(x,y,cal(val,v,op)); vis[x][y] = 0; } } int main() { int T,i,j; cin>>T; while(T--){ f= 1;MS0(vis); scanf("%d%d%lf",&n,&m,&sum); rep(i,n) scanf("%s",s[i] + 1); for(i = 1;i <= n && f;i += 2) for(j = 1;j <= m && f;j += 2){ vis[i][j] = 1; dfs(i,j,s[i][j] - '0'); vis[i][j] = 0; } puts(f?"Impossible":"Possible"); } return 0; }
#include<iostream> #include<cstdio> #include<cstring> #include<string.h> #include<algorithm> #include<map> #include<queue> #include<vector> #include<cmath> #include<stdlib.h> #include<time.h> using namespace std; typedef long long ll; #define MS0(a) memset(a,0,sizeof(a)) ll cal(ll a,ll b,char op) { if(op == '+') return a + b; if(op =='-') return a - b; if(op == '*') return a * b; } int dir[2][4] = {{0,1,0,-1},{1,0,-1,0}}; char s[100][100]; ll sum,f; int n,m,vis[50][50]; void dfs(int i,int j,ll ele,ll den) { if(ele%den == 0 && ele / den == sum) f = 0; ll e = ele, d = den; for(int k = 0;k < 4 && f;k++){ //system("pause"); int x = i + 2*dir[0][k],y = j + 2*dir[1][k]; char op = s[i+dir[0][k]][j+dir[1][k]]; if(x < 1 || x > n || y < 1|| y > m||vis[x][y]) continue; ele = e,den = d; int val = (s[x][y]-'0'); if(op =='/'){ if(val == 0) continue; if(ele % val) den *= val; else ele /= val; } else ele = cal(ele,val,op); if(ele % den == 0) ele /= den,den = 1; vis[x][y] = 1; dfs(x,y,ele,den); vis[x][y] = 0; } } int main() { int T,i,j; cin>>T; while(T--){ MS0(vis); scanf("%d%d%I64d",&n,&m,&sum); for(i = 1;i <= n;i++) scanf("%s",s[i] + 1); f = 1; for(i = 1;i <= n && f;i += 2) for(j = 1;j <= m && f;j += 2){ vis[i][j] = 1; dfs(i,j,(ll)(s[i][j] - '0'),1); vis[i][j] = 0; } puts(f?"Impossible":"Possible"); } return 0; }