Divisibility
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 9562 | Accepted: 3329 |
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
题意:给出n个整数,问在n个整数之间可以任意加上+或-运算符后,是否可以使得式子运算后的结果能被k整除。
思路:每个数mod k的结果都在(-(k-1),k-1)之间。设dp[i][j]=1为运算到第i个数时结果为j,因为有负数,所以全部运算结果都要+k,最后运算完全部数,若dp[n][k]==1,则表示可以被k整除。
AC代码:
#include <iostream> #include <cstdio> #include <cstring> #include <string> #include <algorithm> #include <queue> #include <vector> #include <cmath> #include <stack> #include <cstdlib> using namespace std; const int maxn=10005; bool dp[maxn][300]; int a; int n,k; int main() { while(~scanf("%d%d",&n,&k)) { memset(dp,false,sizeof(dp)); for(int i=1;i<=n;i++) { scanf("%d",&a); if(a<0) a=-a; a%=k; if(i==1) dp[1][k-a]=dp[1][k+a]=true; else { for(int j=0;j<=2*k;j++) if(dp[i-1][j]) { int t=j-a; if(t<0) t=-t; t%=k; dp[i][k-t]=true; t=j+a; t%=k; dp[i][k+t]=true; } } } if(dp[n][k]) printf("Divisible\n"); else printf("Not divisible\n"); } return 0; }