hdu 2151- DP Worm

Worm

Time Limit: 1000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 1835    Accepted Submission(s): 1161

Problem Description
自从见识了平安夜苹果的涨价后,Lele就在他家门口水平种了一排苹果树,共有N棵。
突然Lele发现在左起第P棵树上(从1开始计数)有一条毛毛虫。为了看到毛毛虫变蝴蝶的过程,Lele在苹果树旁观察了很久。虽然没有看到蝴蝶,但Lele发现了一个规律:每过1分钟,毛毛虫会随机从一棵树爬到相邻的一棵树上。
比如刚开始毛毛虫在第2棵树上,过1分钟后,毛毛虫可能会在第1棵树上或者第3棵树上。如果刚开始时毛毛虫在第1棵树上,过1分钟以后,毛毛虫一定会在第2棵树上。
现在告诉你苹果树的数目N,以及毛毛刚开始所在的位置P,请问,在M分钟后,毛毛虫到达第T棵树,一共有多少种行走方案数。
 
Input
本题目包含多组测试,请处理到文件结束(EOF)。 每组测试占一行,包括四个正整数N,P,M,T(含义见题目描述,0<N,P,M,T<100)
 
Output
对于每组数据,在一行里输出一共的方案数。 题目数据保证答案小于10^9
 
Sample Input
3 2 4 2 3 2 3 2
 
Sample Output
4 0
Hint
第一组测试中有以下四种走法: 2->1->2->1->2 2->1->2->3->2 2->3->2->1->2 2->3->2->3->2
 
Author
Linle
 
Source
 
Recommend
lcy
 
 
2012年8月8日  第二次排名赛题目, 一看到题目我就想到了用 深搜, 结果错的很离谱,无论怎么优化都一直超时。下面提出深搜超时代码:
#include <stdio.h>
int n,p,m,T;

int abs(int x)       //取绝对值函数
{ 
return x>=0?x:-x;
}

int Dfs(int x,int t)
{
   
 if(t==m)            //t==m 返回,结束
    {
        if(x==T)
            return 1;
        else 
            return 0;
    }   

    if(abs(T-x)>m-t||abs(T-x)%2!=(m-t)%2)  //剪枝,排除 距离大于时间的情况和奇偶性不同时的情况
         return 0;

    if(x==1)
        return Dfs(x+1,t+1);
    else if(x==n)
        return  Dfs(x-1,t+1);
    else 
         return  Dfs(x-1,t+1)+Dfs(x+1,t+1);
}


int main()
{
    int count;
    while(scanf("%d%d%d%d",&n,&p,&m,&T)!=EOF)
    {
        count=Dfs(p,0);
        printf("%d\n",count);

    }
  return 0;
}


后来自己用DP,轻松就过了....表示很蛋疼....还是做的题太少了....

#include <stdio.h>
#include <string.h>
int main()
{
    int i,j;
    int n,p,t,m;
    int dp[101][101];
    while(scanf("%d%d%d%d",&n,&p,&m,&t)!=EOF)
    {
        memset(dp,0,sizeof(dp));
        dp[p][0]=1;                             //初始化起始点
        for(j=1;j<=m;j++)                      //也很关键,时间从1开始遍历到m
            for(i=1;i<=n;i++)
            dp[i][j]=dp[i-1][j-1]+dp[i+1][j-1];      
        printf("%d\n",dp[t][m]);
    }
  return 0;
}

 

posted @ 2012-08-08 20:51  风之轻吟2012  阅读(286)  评论(0编辑  收藏  举报