hdoj 2151 Worm 【dp】
2015-11-14 21:51
183 查看
Worm
Time Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 3408 Accepted Submission(s): 2195
[align=left]Problem Description[/align]
自从见识了平安夜苹果的涨价后,Lele就在他家门口水平种了一排苹果树,共有N棵。
突然Lele发现在左起第P棵树上(从1开始计数)有一条毛毛虫。为了看到毛毛虫变蝴蝶的过程,Lele在苹果树旁观察了很久。虽然没有看到蝴蝶,但Lele发现了一个规律:每过1分钟,毛毛虫会随机从一棵树爬到相邻的一棵树上。
比如刚开始毛毛虫在第2棵树上,过1分钟后,毛毛虫可能会在第1棵树上或者第3棵树上。如果刚开始时毛毛虫在第1棵树上,过1分钟以后,毛毛虫一定会在第2棵树上。
现在告诉你苹果树的数目N,以及毛毛刚开始所在的位置P,请问,在M分钟后,毛毛虫到达第T棵树,一共有多少种行走方案数。
[align=left]Input[/align]
本题目包含多组测试,请处理到文件结束(EOF)。
每组测试占一行,包括四个正整数N,P,M,T(含义见题目描述,0<N,P,M,T<100)
[align=left]Output[/align]
对于每组数据,在一行里输出一共的方案数。
题目数据保证答案小于10^9
[align=left]Sample Input[/align]
3 2 4 2 3 2 3 2
[align=left]Sample Output[/align]
4 0 Hint 第一组测试中有以下四种走法: 2->1->2->1->2 2->1->2->3->2 2->3->2->1->2 2->3->2->3->2
[align=left]Author[/align]
Linle
[align=left]Source[/align]
ACM程序设计期末考试——2008-01-02(3 教417)
思路:
通过统计在m时刻能够走到p点的次数,就是题上想要的结果。而在求这个的过程中,我们要是知道m-1时刻虫走到p-1点或者走到p+1点就行了,那么我们吧这两种情况加起来就是想要的结果,因此,我们就得到了一个dp方程,就是:dp[m][t]=dp[m-1][t-1]+dp[m-1][t+1];因此通过一个二重循环就能够得到想要的值dp[m][p]了!
但是由题意可知,有一个初始条件就是在0时刻的时候虫在p点!
这道题不能够用bfs,用bfs会出现错误!(Memory Limit Exceeded)不知道为什么?希望大神看到多加指点(在后面附带一个错误代码!)
AC代码:
#include <stdio.h> #include <string.h> #include <algorithm> using namespace std; int n,p,m,t; int dp[101][101]; int main() { while(scanf("%d%d%d%d",&n,&p,&m,&t)!=EOF) { memset(dp,0,sizeof(dp)); dp[0][p]=1;//0分钟在点p的次数为它的值(1) for(int i=1;i<=m;i++) { for(int j=1;j<=n;j++) { // if(dp[i-1][j-1]!=0||dp[i-1][j+1]!=0) // { dp[i][j]=dp[i-1][j-1]+dp[i-1][j+1]; // } } } printf("%d\n",dp[m][t]); } return 0; }
错误代码:
//Memory Limit Exceeded #include <stdio.h> #include <string.h> #include <algorithm> #include <queue> using namespace std; int n,p,m,t; int cnt; struct node { int x,step; }a,temp; int dx[2]={1,-1}; int abs(int a) { if(a<0) return -a; return a; } int judge() { if(temp.step>m) return 0; if(temp.x<1||temp.x>n) return 0; if(abs(temp.x-t)-abs(m-temp.step)>0) return 0; return 1; } void bfs() { a.x=p; a.step=0; queue<node>q; q.push(a); while(!q.empty()) { a=q.front(); q.pop(); for(int i=0;i<2;i++) { temp.x=a.x+dx[i]; temp.step=a.step+1; if(judge()) { if(temp.step==m) { if(temp.x==t) { cnt++; } continue; } q.push(temp); } } } } int main() { while(scanf("%d%d%d%d",&n,&p,&m,&t)!=EOF) { cnt=0; bfs(); printf("%d\n",cnt); } return 0; }
相关文章推荐
- 插入排序Java代码实现
- EditText无法快速响应点击事件
- 装饰者模式-Decorator
- 确认字符ACK
- 软件架构师的12项修炼
- 【linux下配置安装】Utorrent安装使用
- ZOJ 3794 Greedy Driver
- 工厂模式-Factory
- 在Django块标签中遇到的Error:Could not parse the remainder:'>' from 'user.age>'
- 截图
- Tomcat源代码阅读----服务器的启动(2)
- AngularJs ngIf、ngSwitch、ngHide/ngShow
- 【Java小项目】图片浏览器
- shell_of_brief_introduction
- 百度地图开发(四)之POI检索
- UML-面向对象技术
- 生产者模式
- #define的一些
- Android性能调优
- Gym 100796K Profact(爆搜+剪枝)