Poj1745 Divisibility

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Elemmir/article/details/51559277

有N个整数,要求判断能否个这N个数之间添加’+’或’-‘是运算结果是K的倍数。
我们发现K<=100。
于是可以DP了
dp[i][j]表示到第i个数是模K等于j的可行性。

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<iostream>
using namespace std;
const int maxn = 10005;
int f[maxn][105],n,k;
int a[maxn];
#define mod(a,b) ( ((a%b)+b)%b )
int main() {
    scanf("%d%d",&n,&k);
    for (int i = 1; i <= n; i++) scanf("%d",&a[i]);

    f[1][ mod(a[1],k)] = 1;
    for (int i = 2; i <= n; i++)
    for (int j = 0; j < k; j++)
        if( f[i-1][j] ) {
            f[i][ mod(j+a[i],k) ] = 1;
            f[i][ mod(j-a[i],k) ] = 1;
        }
    puts(f[n][0] ? "Divisible" : "Not divisible");
}   
阅读更多

Divisibility

05-05

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:nn17 + 5 + -21 + 15 = 16 n17 + 5 + -21 - 15 = -14 n17 + 5 - -21 + 15 = 58 n17 + 5 - -21 - 15 = 28 n17 - 5 + -21 + 15 = 6 n17 - 5 + -21 - 15 = -24 n17 - 5 - -21 + 15 = 48 n17 - 5 - -21 - 15 = 18 nnWe 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.nnYou are to write a program that will determine divisibility of sequence of integers.nnnInputnnThe first line of the input contains two integers, N and K (1 <= N <= 10000, 2 <= K <= 100) separated by a space. nnThe second line contains a sequence of N integers separated by spaces. Each integer is not greater than 10000 by it's absolute value.nnnOutputnnWrite to the output file the word "Divisible" if given sequence of integers is divisible by K or "Not divisible" if it's not.nnnThis problem contains multiple test cases!nnThe first line of a multiple input is an integer N, then a blank line followed by N input blocks. Each input block is in the format indicated in the problem description. There is a blank line between input blocks.nnThe output format consists of N output blocks. There is a blank line between output blocks.nnnSample Inputnn2nn4 7n17 5 -21 15nn4 5n17 5 -21 15nnnSample OutputnnDivisible nnNot divisible

没有更多推荐了,返回首页