uva10651 Pebble Solitaire(记忆化搜索)

题意:
给定一个长12的由o-组成的字符串,有两种操作。
1."oo-"可以变成"--o".
2."-oo"可以变成"o--".
问通过有限次上述操作后,此符串中最少有几个'o'剩下。
思路:
采取记忆化搜索,因为每个位置上直有两种状态,所以状态总数有 2^12种。然后根据两种操作做递归搜索。
const int maxn = 20;
int dp[1 << 13];
char s[20];
int idx(char str[]) {
    int num = 0;
    for (int i = 0;i < 12;++i) {
        num *= 2;
        if (str[i] == 'o') num += 1;
    }
    return num;
}
int count(char str[]) {
    int num = 0;
    for (int i = 0;i < 12;++i)
        if (str[i] == 'o') num++;
    return num;
}
int solve(char str[]) {
    int u = idx(str);

    if (dp[u] >= 0) return dp[u];

    int& num = dp[u];

    num = count(str);

    for (int i = 1;i < 11;++i) {
        if (str[i] == 'o') {
            if (str[i - 1] == 'o' && str[i + 1] == '-') {
                str[i - 1] = '-', str[i] = '-', str[i + 1] = 'o';

                int cur = solve(str);

                str[i - 1] = str[i] = 'o', str[i + 1] = '-';

                if (cur < num) num = cur;
            }else if (str[i - 1] == '-' && str[i + 1] == 'o') {
                str[i - 1] = 'o', str[i] = str[i + 1] = '-';

                int cur = solve(str);

                str[i - 1] = '-', str[i] = str[i + 1] = 'o';

                if (cur < num) num = cur;
            }
        }
    }
    return num;
}

int main(int argc, const char * argv[])
{   
    // freopen("in.txt","r",stdin);
    // freopen("out.txt","w",stdout);
    int t;
    cin >> t;
    memset(dp, -1,sizeof dp);
    while(t--) {
        cin >> s;
        printf("%d\n", solve(s));
    }
    return 0;
}

你可能感兴趣的:(dp,记忆化搜索)