747:Divisibility

Description

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 file 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.

Sample Input

4 7
17 5 -21 15

Sample Output

Divisible

思路:

dp[i][j]等于true或false表示前i个数的任意组合是否能被k除余数为j ,这样使用的就是动态规划(或者说是记忆化搜索)的思想。 要填写dp[i][j]需要遍历dp[i-1][.],通过第i-1行为true的项dp[i-1][j]以及a[i]的值推导出第i行的值。(这种做法每次都记住了上一次的所有余数的结果,更加明显的证明了动态规划就是记忆化搜索)

这里还发现一个abs的使用区别,如果使用的是中的abs函数,返回值就和参数就是int,如果使用的是中的abs函数,返回值和参数就是double类型。

另外需要注意c++中对于被除数是负数的情况和数学中的不一样,所以**对于有模除运算的地方都要保证被除数变成正数再mod运算!!!

#include
#include
#include
//#include     在cmath中abs返回值和参数是double类型
#include 

//dp[i][j] 表示前i个数的组合能否除以k得到余数j,
//通过dp[i-1][.]的情况,可以得到dp[i][j]情况
 
using namespace std; 

bool dp[10005][105];   //10005是根据n,105是根据k的范围 
int a[10005];

int n,k;

int main(){
	memset(dp,0,sizeof(dp));
	cin>>n>>k;
	for(int i=0;i>a[i];
	//第一行初始化 
	int firstmod=(a[0]+abs(a[0])*k)%k;  //将被除数变成正数再mod k
	dp[0][firstmod]=true;
	for(int i=1;i

 

你可能感兴趣的:(openjudge,dp)