您的位置:首页 > 其它

poj1745-Divisibility(01背包)

2017-04-02 15:13 295 查看
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;

int n, K;
int v[10005];
bool f[10005][105];
struct poj1745 {
/*【问题描述】:有n个数{v1,v2,...,vn},以及一个数K,
* 在这N个数之间添加+或-得到一个表达式,判断该表达式的值能否被K整除
*/

/*【解题思路】:令f
[x]表示前n个数能否通过添加+、-得到一个表达式,
* 使得该表达式的值除以K的余数为x。
* [递推关系]:f
[x]=f[n-1][(x-v
+K*10000)%K]||f[n-1][(x+v
+K*10000)%K],
* [边界条件]:f[0][0]=1
*/

void work() {
while (cin >> n >> K) {
for (int i = 1; i <= n; i++)
cin >> v[i];

memset(f, 0, sizeof(f));
f[0][0] = 1;
for (int i = 1; i <= n; i++) {
for (int j = K - 1; j >= 0; j--) {
f[i][j] = f[i - 1][(j - v[i] + K * 10000) % K] || f[i - 1][(j + v[i] + K * 10000) % K];
}
}

if (f
[0])
cout << "Divisible" << endl;
else
cout << "Not divisible" << endl;
}
}
};
int main()
{
poj1745 solution;
solution.work();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  poj 动态规划 背包