代码参考博客感谢博主!
Divisibility
Time Limit: 2 Seconds Memory Limit: 65536 KB
Consider an arbitrary sequence of integers. One can place + or - operators between integers in the sequence, thus deriving different arithmetical expressions that evaluate to different values. Let us, for example, take the sequence: 17, 5, -21, 15. There are eight possible expressions:
17 + 5 + -21 + 15 = 16
17 + 5 + -21 - 15 = -14
17 + 5 - -21 + 15 = 58
17 + 5 - -21 - 15 = 28
17 - 5 + -21 + 15 = 6
17 - 5 + -21 - 15 = -24
17 - 5 - -21 + 15 = 48
17 - 5 - -21 - 15 = 18
We call the sequence of integers divisible by K if + or - operators can be placed between integers in the sequence in such way that resulting value is divisible by K. In the above example, the sequence is divisible by 7 (17+5+-21-15=-14) but is not divisible by 5.You are to write a program that will determine divisibility of sequence of integers.
Input
The first line of the input contains two integers, N and K (1 <= N <= 10000, 2 <= K <= 100) separated by a space.
The second line contains a sequence of N integers separated by spaces. Each integer is not greater than 10000 by it's absolute value.
Output
Write to the output file the word "Divisible" if given sequence of integers is divisible by K or "Not divisible" if it's not.
This problem contains multiple test cases!The first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.
The output format consists of N output blocks. There is a blank line between output blocks.
Sample Input
24 7
17 5 -21 154 5
17 5 -21 15
Sample OutputDivisible
Not divisible
bool型的dp[i][j]:通过前i个数的运算能否得到余数j.
假设前i个数字运算后得到结果a,a = n*k + b(a>k),a % k = b % k,所以真正有影响的部分是每个数字中不能被k整除的部分,所以表达式中的每个数可以先做%k的处理(正数负数分情况考虑)。
#include <iomanip>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <map>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <algorithm>
#include <iostream>
#define go(i,a,b) for(int i=a;i<=b;i++)
#define og(i,a,b) for(int i=a;i>=b;i--)
#define mem(a) memset(a,false,sizeof(a))
#define IO ios::sync_with_stdio(false);
#define cs cout<<"-----"<<endl;
using namespace std;
const int inf=0x3f3f3f3f;
const int maxn = 1e4 + 5;
typedef long long ll;
bool dp[maxn][105];
int a[maxn];
int main()
{
int n,k,t,r;
cin>>t;
go(r,0,t-1)
{
scanf("%d%d",&n,&k);
mem(dp);
mem(a);
go(i,0,n-1)
{
cin>>a[i];
a[i] = a[i] > 0 ?(a[i] % k) : -(a[i] % k);
}
dp[0][a[0]] = true;
go(i,1,n-1)
{
go(j,0,k)
{
if(dp[i-1][j])
{
dp[i][(j + a[i]) % k] = true;
dp[i][(k + j - a[i]) % k] = true;
}
}
}
if(r != 0)//两行之间输出一行空格的格式
cout<<endl;
printf("%s\n",dp[n - 1][0] ? "Divisible" : "Not divisible");
}
return 0;
}