J - Divisibility
Time Limit:1000MS Memory Limit:10000KB 64bit IO Format:%lld & %llu
Submit
Status
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
- 题意:给一个数列,任意两个数之间可以填+或-,问最后数列的和能不能被k整除;
- 思路:从第一个出发,每一步都有两个选择,遍历时间复杂度指数级;但我们可以发现这个题与数塔问题很像,但是约束条件不同,和数塔解决类似,当前数列的对k的余数可以由前面数列推出 ,f[i,v]={f[i-1,v2]+(-)a[i]%k}%k, f[i,v]代表前i项对k的余数是v,他由前i-1项的余数与第i项对k的余数之和在对k取余(同余定理),具体操作时需要判断i-1项之和的余数是多少;
- 失误:还是太年轻;转移方程的函数一般最后一项表示费用,对于不同问题费用可能不同,应该明确确定费用,然后在将转移函数定义域值域找出来,然后细推解体的步骤,这样才能搞好dp;
- 代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAXN=1e4+10;
int a[MAXN];
bool dp[MAXN][100+11];//dp[i,v]:前i项相加减的余数是v
int main()
{
// printf("%d\n",(-2%3+3)%3); printf("%d\n",-2%3); printf("%d\n",2%-3);
int N,K,i,j;
while(~scanf("%d %d",&N,&K))
{
for(i=1;i<=N;++i)
{
scanf("%d",&a[i]);
if(a[i]<0) a[i]=(a[i]%K+K)%K;//被除数小于0取模不正确
}
memset(dp,false,sizeof(dp));
dp[1][a[1]%K]=true;//第一个数不能加减 他只有一个费用
for(i=2;i<=N;++i)
{
for(j=0;j<K;++j)//选出前i-1项的余数
{
if(dp[i-1][j])//进行当前操作
{
dp[i][(a[i]+j)%K]=true;
dp[i][((j-a[i])%K+K)%K]=true;
}
}
}
printf(dp[N][0]?"Divisible\n":"Not divisible\n");
}
return 0;
}