Divisible judgment

Description] [Title
of a given sequence of positive integers, + or is inserted before each number - the number and calculation thereof. For example, the sequence: 1,2,4 There are eight possible sequences:

(1) + (+2) + (+4) = 7
(1) + (+2) + (-4) = -1
(+1) + (-2) + (+4) = 3
( +1) + (-2) + (-4) = -5
(-1) + (+2) + (+4) = 5
(-1) + (+2) + (-4) = -3
( -1) + (-2) + (+4) = 1
(-1) + (-2) + (-4) = -7
all results in at least one of k may be an integer divisible, we called this a positive integer sequence may be divisible by k. For example, the above sequence may be divisible 3,5,7, 2,4,6,8 ...... can not be divisible. Note: 0, -3, -6, -9 ...... can be considered to be a multiple of 3.

[Enter]
The first line of input contains two numbers: N (2 <N <10000 ) , and k (2 <k <100) , where N represents a total number N, k representative of the dividend. The second line gives the sequence of N integers, are integers ranging between 0 to 10000 (possibly repeated).

[Output]
If the sequence of positive integers k may be divisible, output YES, otherwise the output NO. (Note: all capital letters)

[Sample] input
. 3 2
. 1 2. 4
[Output] Sample
NO
Title Analysis:
The most critical problem is to be understood that the ([n] a [1] + a [2] + ... a)% k = ((a [ 1] + a [2] + ... a [n-1])% k + a [n]% k)% k. If you can not understand went to study number theory foundation congruence theorems, this problem will certainly help to understand.
Before we use f [i] [j] i represents the number of the die and a k value of j, if the value of 1, otherwise to 0.
Thus we know that a set initial conditions f [1] [a [1 ]% k] = 1; it represents a value of a [1]% k k after the first number of mold, so we give it a value of 1 indicates the presence.
Next we extended to the scale of the problem before the number n, the number n and the former value after the upper mold whether j k can be expressed as f [n] [j] = f [n-1] [(j + a [n-1]% k)% k] wherein j + a [n-1] % k)% k = ((a [1] + a [2] + ... + a [n-2])% k + a [n-1] % k)% k = (a [1] + a [2] + ... + a [n-1])% k.
However, meaning of the questions he may add the symbols, formula it becomes f [i] [j] = (f [i-1] [(j + a [i]% k)% k] || f [i-1] [(ja [i]% k + k)% k]). (Wherein (ja [i]% k + k)% k to prevent array bounds).
Code:

#include<iostream>
#include<cmath>
using namespace std;
int a[10001],f[10001][101];
int main()
{
    int n,k;
    cin>>n>>k;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    f[1][a[1]%k]=1;
    for(int i=2;i<=n;i++)
        for(int j=0;j<k;j++)
        f[i][j]=(f[i-1][(j+a[i]%k)%k]||f[i-1][(j-a[i]%k+k)%k]);
    if(f[n][0])
        cout<<"YES";
    else cout<<"NO";
    return 0;
}
Released three original articles · won praise 1 · views 93

Guess you like

Origin blog.csdn.net/amazingee/article/details/104044848