现在的位置: 首页 > 综合 > 正文

UVa #10118 Free Candies (习题9-2)

2018年10月14日 ⁄ 综合 ⁄ 共 1240字 ⁄ 字号 评论关闭

影响决策的条件有二:四个堆最顶端的糖的颜色,以及目前篮子里有什么颜色。

可以用四个指针,分别代表四个堆目前的位置。每次决策有四种:分别从四个堆的顶部取糖果。状态则可以设计成d(p1, p2, p3, p4)代表目前指针的位置为p1, p2, p3, p4,最多可以揣走多少糖果。同时用二进制表达来代表篮子里的糖果颜色种类

Run Time:0.369s

#define UVa  "9-2.10118.cpp"        //Free Candies

#include<cstdio>
#include<vector>
#include<cstring>
#include<string>
#include<algorithm>
#include<iostream>

using namespace std;


//Global Variables.
const int maxn = 40 + 5;
int n;
int piles[maxn][4];
int d[maxn][maxn][maxn][maxn];
int basket[maxn][maxn][maxn][maxn];
int basketsize[maxn][maxn][maxn][maxn];
////

int dp(int p[4]) {
    int& ans = d[p[0]][p[1]][p[2]][p[3]];
    int& b = basket[p[0]][p[1]][p[2]][p[3]];
    int& bsize = basketsize[p[0]][p[1]][p[2]][p[3]];

    if(ans != -1) return ans;
    ans = 0;

    int basketcnt = 0;
    for(int i = 0; i < 4; i ++) {
        if(p[i] >= n) continue;
        int uc = piles[p[i]][i];
        p[i] ++;
        int& vb = basket[p[0]][p[1]][p[2]][p[3]];
        int& vbsize = basketsize[p[0]][p[1]][p[2]][p[3]];
        if(b & (1<<uc)) {        //color matches
            vb = b ^ (1<<uc);
            vbsize = bsize - 1;
            ans = max(ans, dp(p) + 1);
        }
        else {                  //color does not match
            if(bsize < 4) {
                vb = b | (1<<uc);
                vbsize = bsize + 1;
                ans = max(ans, dp(p));
            }
        }
        p[i] --;
    }

    return ans;
}

int main() {s
    while(scanf("%d", &n) && n) {
        for(int i = 0; i < n; i ++)
            for(int j = 0; j < 4; j ++)
                scanf("%d", &piles[i][j]);s

        memset(basket, 0, sizeof(basket));
        memset(basketsize, 0, sizeof(basketsize));
        memset(d, -1, sizeof(d));
        int p[4] = {0,0,0,0};
        printf("%d\n", dp(p));
    }

    return 0;
}

抱歉!评论已关闭.