nefu 627 剪纸游戏(搜索)

来源:互联网 发布:查看域名注册商 编辑:程序博客网 时间:2024/04/28 04:30


剪纸游戏

Time Limit 1000ms

Memory Limit 65536K

description

Recently Raven is addicted to paper cutting games. There is a rectangle-shape paper. Its length is N, and its width is M. On the face side, there are letters in each cell (capital letters A-Z). There are scores on the back side of each letter. A word can be made up of adjacent letters in the paper. Note that adjacency is defined as one of the four following directions only (left, right, up and down). Now a word will be given to you. Please cut this word in the paper to get the highest score of the word. The score of the word is the sum of the score of the letters in the word. 

input

The first line of the input contains an integer T, which indicates the number of test cases.In each case, the first row of each case has two integer: N M, (0 < N,M <= 500)In the following N rows, each row has one string (containing M characters).In the next N rows, each row has M integers divided by space; represent the score of the corresponding letter.The last row has a string (no more than 26 characters) represents the required word to be cut. Input will make sure there are no repeated letters.

output

For each case, output one integer S representing the highest score.If you cannot cut this kind of words, just output -1.

sample_input

13 4ABCDBCDECDEF1 1 1 11 1 2 11 1 1 1ABCD

sample_output

5

#include <iostream>#include <cstdio>#include <cstring>using namespace std;int T,n,m,a[555][555],len,ans,vis[555][555];int dir[4][2]={ {-1,0},{0,-1},{0,1},{1,0} };char s[555][555],str[555];bool check(int x,int y){    if(x>=1 && x<=n && y>=1 && y<=m) return 1;    else return 0;}void dfs(int x,int y,int cur){    if(cur>=len){        ans=max(ans,vis[x][y]);        return;    }    for(int i=0;i<4;i++){        int dx=x+dir[i][0];        int dy=y+dir[i][1];        if(check(dx,dy)&&s[dx][dy]==str[cur]){            if(vis[dx][dy]<vis[x][y]+a[dx][dy]){                vis[dx][dy]=vis[x][y]+a[dx][dy];                dfs(dx,dy,cur+1);            }        }    }}int main(){    scanf("%d",&T);    while(T--){        ans=-1;        memset(vis,0,sizeof(vis));        scanf("%d%d",&n,&m);        for(int i=1;i<=n;i++)            scanf("%s",s[i]+1);        for(int i=1;i<=n;i++){            for(int j=1;j<=m;j++){                scanf("%d",&a[i][j]);            }        }        scanf("%s",str);        len=strlen(str);        for(int i=1;i<=n;i++){            for(int j=1;j<=m;j++){                if(s[i][j]==str[0]){                    vis[i][j]=a[i][j];                    dfs(i,j,1);                }            }        }        printf("%d\n",ans);    }    return 0;}






0 0
原创粉丝点击