UVa 10118 免费糖果(记忆化搜索+哈希)

https://vjudge.net/problem/UVA-10118

题意:

桌上有4堆糖果,每堆有N颗。佳佳有一个最多可以装5颗糖的小篮子。他每次选择一堆糖果,把最顶上的一颗拿到篮子里。如果篮子里有两颗颜色相同的糖果,佳佳就把它们从篮子里拿出来放到自己的口袋里。如果篮子满了而里面又没有相同颜色的糖果,游戏结束。

思路:

怎么判断糖果是否颜色相同是本题的一个重点,看了别人的思路后明白了用哈希是很好的办法。

因为一共只有20颗种类的糖果,所以只需要一个20大小的数组来判断糖果是否出现过。

top[5]数组用来标记每堆糖果所拿的个数。

 #include<iostream>
#include<string>
#include<cstring>
#include<sstream>
#include<algorithm>
using namespace std; const int maxn = ; int n;
int c[][maxn];
int d[maxn][maxn][maxn][maxn];
int top[];
bool Hash[]; int dp(int cur)
{
int& ans = d[top[]][top[]][top[]][top[]];
if (ans) return ans;
if (cur == ) return ; //篮子满了
for (int i = ; i < ; i++)
{
if (top[i] == n) continue; //已经取完
int x = c[i][top[i]++];
if (Hash[x] == true)
{
Hash[x] = false;
ans = max(ans, dp(cur - ) + );
Hash[x] = true;
}
else
{
Hash[x] = true;
ans = max(ans, dp(cur + ));
Hash[x] = false;
}
top[i]--;
}
return ans;
} int main()
{
//freopen("D:\\txt.txt", "r", stdin);
while (cin >> n && n)
{
memset(d, , sizeof(d));
memset(top, , sizeof(top));
memset(Hash, false, sizeof(Hash));
for (int i = ; i < n;i++)
for (int j = ; j < ; j++)
cin >> c[j][i];
cout << dp() << endl;
}
return ;
}
上一篇:Javascript 第五章总结:A trip to Objectville


下一篇:Linux开机流程