zcmu-1710: 整除(dp)
阿新 • • 發佈:2018-11-24
一串數字任意加減運算,求是否能被m整除的題【合集】
(感覺這些題目挺類似的,就放在一起~)
ZOJ-Problem Set - 2042 Divisibility(dp)
1710: 整除
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 305 Solved: 58
[Submit][Status][Web Board]Description
其實,我們知道,如果給你一串序列,例如:17 5 -21 15,我們可以在之間新增上符號(只能是+,或者 - )。使其得出不同的結果:
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現在呢,再給你一個數m(m<=100),就是問你給出的序列s,s的所有組合中是不是存在一種能整除m的,存在的話輸出Yes,沒有的話輸出No
Input
第一行n,m
第二行 n(n<=10000)個數字
Output
輸出Yes or No
Sample Input
4 7 17 5 -21 15
Sample Output
Yes
ZOJ-Problem Set - 2042 Divisibility(dp)跟這題一毛一樣..改個輸出就行了~
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cstdlib> #include <map> #include <list> #include <vector> #include <stack> #include <queue> #include <algorithm> #include <iostream> #define go(i,a,b) for(int i=a;i<=b;i++) #define og(i,a,b) for(int i=a;i>=b;i--) #define mem(a) memset(a,0,sizeof(a)) #define cs cout<<"-----"<<endl; using namespace std; const int inf=0x3f3f3f3f; const int maxn = 1e4 + 5; typedef long long ll; int a[maxn]; bool dp[maxn][105]; int main() { int n,m; while(scanf("%d%d",&n,&m) != EOF) { memset(dp,false,sizeof(dp)); go(i,0,n-1) { scanf("%d",&a[i]); a[i] = a[i] > 0 ? a[i] % m : -(a[i] % m); } dp[0][a[0]] = true; go(i,1,n-1) { go(j,0,m-1) { if(dp[i-1][j]) { dp[i][(j+a[i]) % m] = true; dp[i][(m+j-a[i]) % m] = true; } } } printf("%s\n",dp[n-1][0] ? "Yes":"No"); } return 0; }