标签:
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others) Total Submission(s): 1210 Accepted Submission(s): 316
题解:让dfs表达式计算看能不能得到sum,必须是紧挨着的运算;
很好的一道搜索题,本来自己写了半天,各种考虑啊,然并卵,看了大神的解释,直接每次走两步就好了,那就简单多了,写了下就过了,Impossible i没大写错了一次;
发现dfs有时候真的很需要找对方法,否则麻烦还容易错;由于有除法运算,所以有误差,1e-8判断下误差;还有就是除以0的情况也考虑下;
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<map> #include<string> #include<vector> using namespace std; const int INF=0x3f3f3f3f; #define SI(x) scanf("%d",&x) #define PI(x) printf("%d",x) #define P_ printf(" ") #define mem(x,y) memset(x,y,sizeof(x)) typedef __int64 LL; const int MAXN=20; char mp[MAXN][MAXN]; int disx[4]={0,0,2,-2}; int disy[4]={2,-2,0,0}; double sum; int flot; int n,m; bool isjs(char a){ if(a==‘+‘||a==‘-‘||a==‘*‘||a==‘/‘)return true; else return false; } double js(double a,char x,double b){ switch(x){ case ‘+‘:return a+b;break; case ‘-‘:return a-b;break; case ‘*‘:return a*b;break; case ‘/‘:return a/b;break; } } void dfs(int x,int y,double cur){ if(flot)return; if(abs(cur-sum)<=1e-8){ flot=1; return; } for(int i=0;i<4;i++){ int nx=x+disx[i],ny=y+disy[i]; if(nx<0||ny<0||nx>=n||ny>=m)continue; if(!isdigit(mp[nx][ny]))continue; if(!isjs(mp[x+disx[i]/2][y+disy[i]/2]))continue; char temp=mp[nx][ny]; // printf("%I64d %c %c ",cur,mp[x+disx[i]/2][y+disy[i]/2],mp[nx][ny]); // printf("%I64d\n",js(cur,mp[x+disx[i]/2][y+disy[i]/2],mp[nx][ny]-‘0‘)); if(mp[x+disx[i]/2][y+disy[i]/2]==‘/‘&&mp[nx][ny]==‘0‘)continue; double t=js(cur,mp[x+disx[i]/2][y+disy[i]/2],mp[nx][ny]-‘0‘); mp[nx][ny]=‘#‘; dfs(nx,ny,t); mp[nx][ny]=temp; } } int main(){ int T; SI(T); while(T--){ scanf("%d%d%lf",&n,&m,&sum); for(int i=0;i<n;i++)scanf("%s",mp[i]); flot=0; for(int i=0;i<n;i++){ for(int j=0;j<m;j++){ if(isdigit(mp[i][j])){ int temp=mp[i][j]-‘0‘; mp[i][j]=‘#‘; dfs(i,j,temp); mp[i][j]=temp+‘0‘; } } } // for(int i=0;i<n;i++)puts(mp[i]); if(flot)puts("Possible"); else puts("Impossible"); } return 0; }
Baby Ming and Matrix games(dfs计算表达式)
标签:
原文地址:http://www.cnblogs.com/handsomecui/p/5256910.html