UVA 11882 Biggest Number (dfs搜索+bfs 剪枝)

来源:互联网 发布:淘宝朋友代付怎么查看 编辑:程序博客网 时间:2024/05/20 07:53

大体题意:

给你一个r*c的数字矩阵,要求从任意一个点开始走,只能上下左右走, 求走的过数连接起来最大是多少?

思路:

直接dfs每一个数字,在每一层dfs中,加上bfs 判断剩下的数连接起来能否大于当前的ans 不能的话 剪枝了。

虽然思路是这样的,但昨天一直TLE, 或许姿势不对,第二天重写了一遍 就好很多了= =

#include <cstdio>#include <cstring>#include <algorithm>#include <string>#define Siz(x) (int)x.size()using namespace std;const int maxn = 30 + 7;int anslen;string ans;int q[10000000 + 7], L, R;void camp(string& ss){    int len = Siz(ss);    if (len > anslen) {        ans = ss;        anslen = len;    }    else if (len == anslen && ans < ss) ans = ss;}int n,m;char s[maxn][maxn];bool vis[maxn][maxn];const int dx[] = {1,-1,0,0};const int dy[] = {0,0,-1,1};bool bfs_vis[maxn][maxn];bool cmp(char& ch1,char& ch2){    return ch1 > ch2;}bool not_go(int &x_,int &y_,string &o){    L = R = 0;    q[R++] = x_ * 100+y_;    memset(bfs_vis,0,sizeof bfs_vis);    bfs_vis[x_][y_] = 1;    string tmp = o;    while(L < R){        int oo = q[L++];        int y = oo%100; oo-=y;        int x = oo/100;        for (int i = 0; i < 4; ++i){            int xx = x + dx[i];            int yy = y + dy[i];            if (xx >= 0 && xx < n && yy >= 0 && yy < m && s[xx][yy] != '#' && !vis[xx][yy] && !bfs_vis[xx][yy]){                bfs_vis[xx][yy] = 1;                tmp += s[xx][yy];                q[R++] = (xx*100+yy);            }        }    }    int len = Siz(tmp);    if (len < anslen) return 1;    else if (len == anslen){        int olen = Siz(o);        sort(tmp.begin()+olen,tmp.end(),cmp);        if (tmp <= ans) return 1;        return 0;    }    return 0;}void dfs(int x,int y,string o){    if (anslen){        if (not_go(x,y,o)) return;    }    bool ok = 0;    for (int i = 0; i < 4; ++i){        int xx = x + dx[i];        int yy = y + dy[i];        if (xx >= 0 && xx < n && yy >= 0 && yy < m && s[xx][yy] != '#' && !vis[xx][yy]){            vis[xx][yy] = 1;            ok = 1;            dfs(xx,yy,o+s[xx][yy]);            vis[xx][yy] = 0;        }    }    if (!ok){        camp(o);    }}void init(){    anslen = 0;    ans= "";}int main(){    while(~scanf("%d %d",&n, &m) && (n || m)){        for (int i = 0; i < n; ++i){            scanf("%s",s[i]);        }        init();        for (int i = 0; i < n; ++i){            for (int j = 0; j < m; ++j){                if (s[i][j] != '#'){                    memset(vis,0,sizeof vis);                    vis[i][j] = 1;                    string a = "";                    a += s[i][j];                    dfs(i,j,a);                }            }        }        printf("%s\n",ans.c_str());    }    return 0;}/**3 7##9784###123####45###0 0791452384**/


0 0
原创粉丝点击