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

23 篇文章 0 订阅
12 篇文章 0 订阅

大体题意:

给你一个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 0
791452384
**/


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值