百练1745:Divisibility

E:Divisibility

总时间限制: 
1000ms 
内存限制: 
65536kB
描述
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. 
输入
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. 
输出
Write to the output file the word "Divisible" if given sequence of integers is divisible by K or "Not divisible" if it's not.
样例输入
4 7
17 5 -21 15
样例输出
Divisible
来源

Northeastern Europe 1999

*****************************************

这道题。。。。简直了,几天不做题马上手生。这道题应该用dp做,因为其实他具有dp题的特点,即“一点一点的”(整个加/减法过程是一点一点进行的),然而我一开始试图用DFS,递归,但就算做出来估计也是超时的。但是dp的状态不好选取。本题定义dp[i][j]为取前i个数对k取余是否为j,是则为1,不是则为0,初始状态为dp[1][a[1]%k]=1.就是每次用余数去加下一个数再去算余数。原因是,除了余数之外的部分,可以被认为可以被k整除了,所以可以舍弃掉,不必考虑。所以整个算是的值能否被k整除,其实也就是考虑每次运算的余数都处理过一遍之后,能否整除。

参考这位大神的博客:

http://blog.csdn.net/wangjian8006/article/details/10170671

代码也是人家的

#include <iostream>  
using namespace std;  
#define MAXN 10001  
  
int dp[MAXN][101];  
  
int posmod(int n,int k){        正数取余  
    n = n % k;  
    while(n < 0) n+=k;  
    return n;  
}  
  
int main(){  
    int n,k;  
    int i ,j ,tmp;  
    int a[MAXN];  
    while(cin>>n>>k){  
        memset(dp,0,sizeof(dp));  
        for(i = 1;i <= n;i++) cin>>a[i];  
        dp[1][posmod(a[1],k)] = 1;  
        for(i = 2;i <= n;i++){  
            for(j = 0;j < k;j++){  
                if(dp[i - 1][j]){  
                    dp[i][posmod(j + a[i],k)] = 1;  
                    dp[i][posmod(j - a[i],k)] = 1;  
                }  
            }  
        }  
        if(dp[n][0]){  
            cout<<"Divisible"<<endl;  
        }else{  
            cout<<"Not divisible"<<endl;  
        }  
    }  
    return 0;  
}  
****************************

坚持,胜利就在眼前了~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值