题目链接:
http://poj.org/problem?id=1745
题意:
给出N个数a[i],在中间填上加号或减号,问能否出现一种填法使和能被K整除
题解:
我们可以 bool dp[i][j] = true 表示前i个数的和可能出现j,再通过dp[i][j] = true 当dp[i-1][j-a[i]] = true 或 dp[i-1][j+a[i]] = true,然后我们再枚举j = nk (n=1,2,...)判断是否存在dp[N][nk],但是由于每个数的绝对值最大为10000并且最多有10000个数,所以这样不可行。但是由于(a+b) mod c == a mod c + b mod c 所以 dp[i][j] = true 当dp[i-1][(j-a[i])%k] = true 或 dp[i-1][(j+a[i])%k] = true。不过还要注意和为负数的问题。
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<cmath>
#include<stdlib.h>
#include <string.h>
#include<queue>
#include<set>
#include<map>
#include<stack>
#include<time.h>
using namespace std;
#define MAX_N 100005
#define inf 0x3f3f3f3f
#define LL long long
#define ull unsigned long long
const LL INF = 1e18;
const int mod = 1e8+7;
typedef pair<int, int>P;
bool dp[10005][205];
int main()
{
int N, K;
cin >> N >> K;
int x;
dp[0][100] = true;
for(int i=0; i<N; i++) {
scanf("%d", &x);
for(int j=-100; j<=100; j++) {
if(dp[i][j+100]) {
dp[i+1][(j+x)%K+100] = true;
dp[i+1][(j-x)%K+100] = true;
}
}
}
if(dp[N][100])
puts("Divisible");
else
puts("Not divisible");
}