程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> POJ 1745 Divisibility (線性dp)

POJ 1745 Divisibility (線性dp)

編輯:C++入門知識

POJ 1745 Divisibility (線性dp)



Divisibility Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 10598 Accepted: 3787

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

Source

Northeastern Europe 1999

題目鏈接:http://poj.org/problem?id=1745

題目大意:給n個數,讓他們通過加減運算,判斷結果可不可能被k整除

題目分析:用dp[i][j]表示通過前i個數的運算得到的余數為j可不可能,先看求a % k,如果a > k,則a = n * k + b,(n * k + b) % k == 0 + b % k = a % k,所以當a > k時,對求余數有影響的部分是不能被整除的部分,因此對於每個數我們可以做a[i] = a[i] > 0 ? (a[i] % k) : -(a[i] % k)的預處理,然後就是在dp[i - 1][j]的情況下,推出下一狀態,下一狀態有兩種可能,加和減,減的時候防止出現負數加上個k再取余,初始化dp[0][a[0]] = true最後只要判斷dp[n - 1][0]及前n個數通過加減運算能否得到被k整除的值

#include 
#include 
int const MAX = 10005;

bool dp[MAX][105];
int a[MAX];

int main()
{
    int n, k;
    while(scanf("%d %d", &n, &k) != EOF)
    {
        memset(dp, false, sizeof(dp));
        for(int i = 0; i < n; i++)
        {
            scanf("%d", &a[i]);
            a[i] = a[i] > 0 ? (a[i] % k) : -(a[i] % k);
        }
        dp[0][a[0]] = true;
        for(int i = 1; i < n; i++)
        {
            for(int j = 0; j <= k; j++)
            {
                if(dp[i - 1][j])
                {
                    dp[i][(j + a[i]) % k] = true;
                    dp[i][(k + j - a[i]) % k] = true;
                }
            }
        }
        printf("%s\n", dp[n - 1][0] ? "Divisible" : "Not divisible");
    }
}


  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved