Divisibility
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 11534 | Accepted: 4138 |
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.
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.
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
Source
题意给你n个数在其中添加n-1个符号'-' '+';满足最后的结果能够整除K
看着挺难,仔细分析,你会想到把所有的情况都列举不就行了,其实我自我感觉代码的原理也是这样的
想一想;同余定理 (a+b)%c==(a%c+b%c)%c 我们把每一个值进行对k取模,然后对下一个值取模的进行
加 减 并标记为1,以进行下一次的运算
都说是动态规划题,我正在学,目前没有看出来@_@s
#include<cstdio>
#include<cstring>
int dp[10000+11][110];
int num[10000+11];
int main()
{
int n,k;
while(scanf("%d%d",&n,&k)!=EOF)
{
int i,j;
memset(dp,0,sizeof(dp));
for(i=1;i<=n;++i)
scanf("%d",&num[i]);
dp[0][0]=1;
for(i=1;i<=n;++i)
{
for(j=0;j<k;++j)
{
if(dp[i-1][j])
{
//主要考虑到存在负数的情况
int t=((j-num[i])%k+k)%k;
dp[i][t]=1;
t=((j+num[i])%k+k)%k;
dp[i][t]=1;
}
}
}
//t其实就是最后的运算结果,当t=0时,就代表着整除了,相应的就会有dp[n][0]=1;
//如果不能整除,那就不会出现t=0的情况,dp[n][0]的初始值就不会改变
if(dp[n][0])
printf("Divisible\n");
else
printf("Not divisible\n");
}
return 0;
}