博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
POJ 1745 Divisibility【DP】
阅读量:5790 次
发布时间:2019-06-18

本文共 2315 字,大约阅读时间需要 7 分钟。

Language:Default
Divisibility
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 8396   Accepted: 2909

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 717 5 -21 15

Sample Output

Divisible

题意:给出n个数,在n个数中添加+,-号使得能整除k.

思路:由于状态与前一个数有关,且和第i个数+或-有关。dp[i][j]表示第i个数余数为j时是否为真,dp[i][j-a[i]%m]=dp[i-1][j], dp[i][j+a[i]%m]=dp[i-1][j];判断dp[m][0]是否为真即可,初始条件是dp[1][a[1]]=1;但是注意一点下标不能为负数为此+k*n是等价的。

代码如下:

#include
#include
#include
using namespace std;int dp[10005][105], a[10005];int main(){ int i, j, k, n; while(scanf("%d%d", &n, &k)!=EOF) { memset(dp, 0, sizeof(dp)); memset(a, 0, sizeof(a)); for(i=1; i<=n; i++) { scanf("%d", &a[i]); a[i]%=k; } while(a[1]<0) a[1]+=k; dp[1][a[1]%k]=1; for(i=2; i<=n; i++) for(j=0; j<=k; j++) if(dp[i-1][j]) { int aa=j-a[i], bb=j+a[i]; while(aa<0) aa+=k; while(bb<0) bb+=k; dp[i][aa%k]=1, dp[i][bb%k]=1; } if(dp[n][0]==1) printf("Divisible\n"); else printf("Not divisible\n"); }}

 

转载于:https://www.cnblogs.com/Hilda/archive/2012/07/31/2616816.html

你可能感兴趣的文章
JProfiler学习笔记
查看>>
Loadrunner脚本编程(4)-数据类型操作和字符串操作
查看>>
STL 算法
查看>>
分享:Backbone.js 样例站点与入门指南
查看>>
图的基本算法
查看>>
《架构之美》摘录三
查看>>
HTML基础(一)
查看>>
boost.circular_buffer简介
查看>>
Database Appliance并非Mini版的Exadata-还原真实的Oracle Unbreakable Database Appliance
查看>>
网页图片缩放(js)
查看>>
Perl开发的几个小注意事项
查看>>
SQL Server数据库备份恢复常见问题(不断更新中)
查看>>
实现hive proxy1-hive认证实现
查看>>
LinuxShell脚本之利用rsync+ssh实现Linux文件系统远程备份
查看>>
设计和使用维护计划
查看>>
Hyper-V 2016 系列教程3 Hyper-V 组件的添加
查看>>
func install in ubuntu-server
查看>>
PostgreSQL数据库pg_dump命令行不输入密码的方法
查看>>
asp教程八:访问数据库
查看>>
Linux 文件系统权限记序
查看>>