POJ 1745

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  

题目大意:在所给的N个数当中(所有的数都必需用一遍),运用适当的加减运算求出是否存在这N个数的运算结果能够被K整除。

用暴力想过找到这样的数据就break就行,但如果有10000个数那怎么实现,暴力很难实现,所以考虑用DP(要经过很长时间看 题 解大哭

由(a+b)%k=(a%K+b%K)%K可以推出,将所有的数分开来算,不就是余数的累加吗(即当前项是由前一项推出)

用dp[i][j]表示前i个数中余数是否是j;

首先第一项的余数就是固定的(存在负数的情况要处理),拿样例来说dp[0][(a[0]%k+k)%k]==1;    17%7=4;

所以只有这一项是1;其他dp[0][j](在样例当中j,也就是余数的范围是从0到6)都不存在就是0,那就继续往下当为a[i]=5时,

只能从上一个dp[0][4]继续往下推(因为首项没有其他余数嘛),只有+-两种情况,所以对5的余数看看有哪些,继续往下推出

#include<iostream>
using namespace std;
typedef long long ll;
int a[10005];
int dp[10005][105];

int main()
{
        int n,k;
        cin>>n>>k;
        for(int i=0;i<n;i++)
            cin>>a[i];
        dp[0][(a[0]%k+k)%k]=1;
        for(int i=1;i<n;i++)
        {
            for(int j=0;j<k;j++)
                if(dp[i-1][j])//前一项j的余数存在
            {
                dp[i][((j+a[i])%k+k)%k]=1;//前一项的余数加当前的a[i],其中加K是防止为负数,同下;
                dp[i][((j-a[i])%k+k)%k]=1;
            }
        }
//        for(int i=0;i<n;i++)
//        {
//            for(int j=0;j<k;j++)
//                cout<<dp[i][j]<<" ";
//            cout<<endl;
//        }
        dp[n-1][0]==1 ? cout<<"Divisible"<<endl: cout<<"Not divisible"<<endl;
        return 0;
}

猜你喜欢

转载自blog.csdn.net/c___c18/article/details/80691002
POJ