百练1745:Divisibility

来源:互联网 发布:apache bench post 编辑:程序博客网 时间:2024/05/06 03:20

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 717 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;  }  
****************************

坚持,胜利就在眼前了~

原创粉丝点击