棋盘寻宝扩展(微策略2012年校园招聘笔试题)

题目1532:棋盘寻宝扩展

时间限制:1 秒

内存限制:128 兆

特殊判题:

提交:155

解决:72

题目描述:

现在有一个8*8的棋盘,上面放着64个不同价值的礼物,每个小的棋盘上面放置一个礼物(礼物的价值大于0小于100),一个人初始位置在棋盘的左上角,每次他只能向下或向右移动一步,并拿走对应棋盘上的礼物,结束位置在棋盘的右下角。从棋盘的左上角移动到右下角的时候的,每次他只能向下或向右移动一步,并拿走对应棋盘上的礼物,但是拿到的所有的礼物的价值之和不大于一个限定值limit,请设计一个算法请实现,使其能够获得不超过限制值limit的最大价值的礼物。

输入:

输入包含多个测试用例,每个测试用例共有9行,第一行是一个限制值limit<=1000,下面还有8行8列,第i行的第j列的数字代表了该处棋盘上的礼物的价值,每两个数之间用空格隔开。

输出:

对于每组测试用例,请输出你能够获得不超过限制值limit的最大价值的礼物。若没有符合条件的线路则输出-1。

样例输入:
90
4 2 5 1 3 8 9 7
4 5 2 3 7 1 8 6
7 2 1 8 5 9 3 6
2 8 9 5 6 3 1 7
1 2 4 5 3 7 9 6
3 5 7 8 9 6 2 4
10 8 1 4 7 5 3 9
7 4 6 2 1 3 9 8
样例输出:
90
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 10;

struct info {
    int x;
    int y;
    int tot;
};

int v[maxn][maxn];
int limit;

void init() {
    int i, j;
    for(i = 1; i <= 8; i++) {
        for(j = 1; j <= 8; j++) {
            scanf("%d", &v[i][j]);
        }
    }
}

void work() {
    int result = 0;
    info start, extend;
    start.x = start.y = 1;
    start.tot = v[1][1];
    queue<info> Q;
    while(!Q.empty()) Q.pop();
    Q.push(start);
    while(!Q.empty()) {
        info tmp = Q.front();
        Q.pop();
        if(tmp.x + 1 <= 8) {
            if(tmp.tot + v[tmp.x + 1][tmp.y] <= limit) {
                extend.x = tmp.x + 1;
                extend.y = tmp.y;
                extend.tot = tmp.tot + v[tmp.x + 1][tmp.y];
                Q.push(extend);
                if(tmp.x + 1 == 8 && tmp.y == 8) {
                    result = max(result, extend.tot);
                }
            }
        }
        if(tmp.y + 1 <= 8) {
            if(tmp.tot + v[tmp.x][tmp.y + 1] <= limit) {
                extend.x = tmp.x;
                extend.y = tmp.y + 1;
                extend.tot = tmp.tot + v[tmp.x][tmp.y + 1];
                Q.push(extend);
                if(tmp.y + 1 == 8 && tmp.x == 8) {
                    result = max(result, extend.tot);
                }
            }
        }
    }
    if(result == 0)
        printf("-1\n");
    else 
        printf("%d\n", result);
}

int main()
{
    while(scanf("%d", &limit) != EOF) {
        init();
        work();
    }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值