poj 1745 Divisibility

本文介绍了一种通过动态规划解决特定整除问题的方法。针对一系列整数,可以通过添加加号或减号来判断最终结果是否能被给定的整数K整除。文章详细解释了如何使用二维布尔数组dp来跟踪所有可能的余数状态。

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


大意:
  输入n,k,然后有n个数,可以在n个数之间随意添加加号或减号判断最后的值能不能别k整除。

定义数组dp[i][j]表示第i个数对k取余为j,(a[1]%k+k)%k为a[1]对k取余的值,所以定义dp[i][(a[1]%k+k)%k]=true;令i从2~n,余数j从0~k-1,判断a[i-1][j]求出a[i-1]余数j,求出j+a[i]或j-a[i]对k取余的值,定义a[i][((j(+或-)a[i])%k+k)%k]=true,若dp[n][0]为真,表示a[n]加上前面的余数对k取余为0。
 
 1 #include<cstdio>
 2 #include<string.h>
 3 bool dp[10010][110];
 4 int main()
 5 {
 6     int n,k,i,j,a[10010];
 7     while(scanf("%d %d",&n,&k)!=EOF)
 8     {
 9         memset(dp,false,sizeof(dp));
10         for(i = 1 ; i <= n ; i++)
11         {
12             scanf("%d",&a[i]);
13         }
14         dp[1][(a[1]%k+k)%k]=true;            //(a[1]%k+k)%k为a[1]对k取余的值(加k为了避免取余结果为负值) 
15         for(i = 2 ; i <= n ; i++)
16         {
17             for(j = 0 ; j < k ; j++)
18             {
19                 if(dp[i-1][j])                //令a[i-1]对k取余的值加上a[i]再对k取余 
20                 {
21                     dp[i][((j+a[i])%k+k)%k]=true;
22                     dp[i][((j-a[i])%k+k)%k]=true;
23                 }
24             }
25         }
26         if(dp[n][0])                        //为真时说明a[n]加前面的余数对k取余为0 
27         {
28             printf("Divisible\n");
29         }
30         else
31         {
32             printf("Not divisible\n");
33         }        
34      } 
35     return 0;
36 }

 

转载于:https://www.cnblogs.com/yexiaozi/p/5753487.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值