Baby Ming and Matrix games
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 1257 Accepted Submission(s): 330
Problem Description
These few days, Baby Ming is addicted to playing a matrix game.
Given a
n∗m
matrix, the character in the matrix
(i∗2,j∗2) (i,j=0,1,2...)
are the numbers between
0−9 . There are an arithmetic sign (‘+’, ‘-‘, ‘
∗ ’, ‘/’) between every two adjacent numbers, other places in the matrix fill with ‘#’.
The question is whether you can find an expressions from the matrix, in order to make the result of the expressions equal to the given integer
sum . (Expressions are calculated according to the order from left to right)
Get expressions by the following way: select a number as a starting point, and then selecting an adjacent digital X to make the expressions, and then, selecting the location of X for the next starting point. (The number in same place can’t be used twice.)
Input
In the first line contains a single positive integer
T , indicating number of test case.
In the second line there are two odd numbers
n,m , and an integer sum(
−1018<sum<1018 , divisor 0 is not legitimate, division rules see example)
In the next
n
lines, each line input
m
characters, indicating the matrix. (The number of numbers in the matrix is less than
15 )
1≤T≤1000
Output
Print Possible if it is possible to find such an expressions.
Print Impossible if it is impossible to find such an expressions.
Sample Input
3
3 3 24
1*1
+#*
2*8
1 1 1
1
3 3 3
1*0
/#*
2*6
Sample Output
Possible
Possible
Possible
Hint
The first sample:1+2*8=24 The third sample:1/2*6=3
Source
BestCoder Round #69 (div.2)
Recommend
hujie | We have carefully selected several similar problems for you: 5649 5648 5647 5646 5645
深搜找出所有答案,只是注意浮点数的比较问题;
#include<iostream>
#include<cstdlib>
#include<string>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<stack>
#include<queue>
#include<iomanip>
#include<map>
#include<set>
#include<functional>
#define pi 3.14159265358979323846
using namespace std;
int dx[]={1,-1,0,0};
int dy[]={0,0,1,-1};
int n,m;
double sum;
bool vis[30][30];
char maze[30][30];
bool flag;
void dfs(int x,int y,double cursum)//cursum为当前的结果
{
if(fabs(cursum-sum)<1e-7)
{
flag=1;
return ;
}
if(flag==1)
{
return ;
}
for(int k=0;k<4;++k)
{
int tx=x+dx[k]*2,ty=y+dy[k]*2;
if(tx<1||tx>n||ty<1||ty>m||vis[tx][ty])
continue;
char cal=maze[x+dx[k]][y+dy[k]];
int tnum=maze[tx][ty]-'0';
vis[tx][ty]=1;
if(cal=='+') dfs(tx,ty,cursum+tnum);
if(cal=='-') dfs(tx,ty,cursum-tnum);
if(cal=='*') dfs(tx,ty,cursum*tnum);
if(cal=='/') dfs(tx,ty,cursum/tnum);
vis[tx][ty]=0;
}
}
int main()
{
int T;
scanf("%d",&T);
while(T--)
{
flag=0;
memset(vis,0,sizeof(vis));
scanf("%d %d %lf",&n,&m,&sum);
for(int i=1;i<=n;++i)
{
scanf("%s",maze[i]+1);
}
for(int i=1;i<=n;i+=2)
for(int j=1;j<=m;j+=2)
{
vis[i][j]=1;
dfs(i,j,maze[i][j]-'0');
vis[i][j]=0;
if(flag) break;
}
if(flag)
puts("Possible");
else
puts("Impossible");
}
return 0;
}