回 帖 发 新 帖 刷新版面

主题:请问怎么样优化该题。。。(超时了)

In Spring Time University (STU), there is a small park. The roads of the park looks like an M*M chessboard. There is only two gate, one is in the northwest of the park,the other is in the southwest of the park . LJ wants to stroll through the park and pass through all the crossing, but he doesn't know how many ways he can do that,please help him.

  

Now, this is one way to stroll through a 3*3 park.



Input
each input line contains one small number M (2<=M<=6)

  

Output
each output line also contains only one number W----the ways.

  

Sample Input
2

Sample Output
2
这是题的网址http://acm.stu.edu.cn/cgi-bin/problem?id=1031
下面是我的程序
#include<stdio.h>
int jzh[10][10],point;long num;
find(int i,int j,int n)
  { if ((i==n)&&(j==0)&&(point==((n+1)*(n+1)-1)))
         num++;
    if ((i<n)&&(jzh[i+1][j]))
     { jzh[i+1][j]=0;
        point++;
       find(i+1,j,n);
       jzh[i+1][j]=1;
        point--;
      }
     if ((j<n)&&(jzh[i][j+1]))
    { jzh[i][j+1]=0;
        point++;
       find(i,j+1,n);
       jzh[i][j+1]=1;
        point--;
      }
    if ((i>0)&&(jzh[i-1][j]))
     { jzh[i-1][j]=0;
        point++;
       find(i-1,j,n);
       jzh[i-1][j]=1;
        point--;
      }
    if ((j>0)&&(jzh[i][j-1]))
    { jzh[i][j-1]=0;
        point++;
       find(i,j-1,n);
       jzh[i][j-1]=1;
        point--;
      }
   }
int main()

  {  int n,j,i;
     while(scanf("%d",&n)!=EOF)
      { point=0;num=0;
        for(i=0;i<=n;i++)
         for(j=0;j<=n;j++)
           jzh[i][j]=1;
           jzh[0][0]=0;
        i=j=0;
        find(i,j,n);
        printf("%ld\n",num);
       }
   }

回复列表 (共7个回复)

沙发

可以用回溯法解

板凳

我是用回溯做的,但是超时了,
我又不知道怎么优化,
请各位高手指点一下。。。。
thx

3 楼

凭感觉用动态规划。
这题数据太小了可以钻空子,你用弱方法把解都求出来了,然后简单输出就是了。

4 楼

什么办法啊?
我用回溯(上面的程序)做,
输入5,大概几秒钟就输出,
当输入6后,
等了N久都没有输出。。。

5 楼

就是把所有结果保存在一个文件里面,然后把保存的内容放在一个数组里面,直接读取就可以了。

6 楼

那怎么得到结果啊?根本就算不出结果。。。

7 楼

就是交表咯~我搜n=6的是要15s才出结果,而且是剪了枝的,不知道人家怎么过的呢?
#include<stdio.h>
int main()
{
    int n;
    while (scanf("\n%d",&n) !=EOF)
    {
        if (n < 2) break;
        if (n == 2) printf("2\n");
        else if (n == 3) printf("8\n");
        else if (n == 4) printf("86\n");
        else if (n == 5) printf("1770\n");
        else if (n == 6) printf("88418\n");
    }
    return(0);
}

我来回复

您尚未登录,请登录后再回复。点此登录或注册