NEFU 627

http://acm.nefu.edu.cn/JudgeOnline/problemshow.php?problem_id=627

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

1
3 4
ABCD
BCDE
CDEF
1 1 1 1
1 1 2 1
1 1 1 1
ABCD

sample_output

5

一道搜索的题目,本来不算很难,不知道为什么输出上有问题。比赛的时候没有做出来,晚上回来改了改输出就对了,至今不明白为什么会错。

代码:

#include <string.h>
#include <stdio.h>
#include <iostream>
using namespace std;
int b[1005][1005];
char a[1005][1005],c[30];
int tt,ans,m,maxx,dd,n;
void dfs(int x,int y,int k)
{
    if(k>=dd)
    {
        if(maxx<ans)
             maxx=ans;
        return;
    }
    int tx[]={1,-1,0,0};
    int ty[]={0,0,-1,1};
    for(int i=0;i<4;i++)
    {
        int xx=tx[i]+x;
        int yy=ty[i]+y;
        if(a[xx][yy]==c[k]&&xx>=0&&xx<n&&yy>=0&&yy<m)
        {
            ans+=b[xx][yy];
            dfs(xx,yy,k+1);
            ans-=b[xx][yy];
        }
    }
}
int main()
{
    int t;
    scanf("%d",&t);
    while(t--)
    {
        memset(c,0,sizeof(c));
        memset(a,0,sizeof(a));
        scanf("%d%d",&n,&m);
        getchar();
        for(int i=0;i<n;i++)
           scanf("%s",a[i]);
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
            {
                scanf("%d",&b[i][j]);
            }
        scanf("%s",c);
        dd=strlen(c);
        int d;
        maxx=-1;
        for(int i=0;i<n;i++)
            for(int j=0;j<m;j++)
            if(a[i][j]==c[0])
            {
                ans=b[i][j];
                dfs(i,j,1);
            }
        printf("%d\n",maxx);
    }
    return 0;
}


你可能感兴趣的:(NEFU 627)