【URAL 1260】 DP (dfs打表之后找规律也行)

题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1260

 

题目大意:有n个数1—n,将他们排成一列。最左边必须是1,后面排列的数字和与他们它们相邻的数字只差不能超过2,求有多少中排列方式。

 

解题思路:

一开始看到这题,才55个点,果断dfs,结果TLE。不过至少答案是正确的,然后把答案给记录起来,仔细一分析,发现有规律可寻,打表,果断过了。

规律递推式:dp[n]=dp[n-1]+dp[n-3]+1。

 

搜狗一下发现别人此题写的是DP,囧。

然后又思考了一下,果然如此。

n个人时求dp[n]。第2个位置放2时有dp[n-1]种;第2个位置放3,第3个位置放2,第4个位置只能放4,有dp[n-3]种;第2个位置放3,第3个位置放5,13578642,有1种;第2个位置放3,第3个位置不能放4。

 

dfs超时代码

 1 #include <iostream>

 2 #include <cstdio>

 3 #include <algorithm>

 4 #include <cstring>

 5 using namespace std;

 6 

 7 int color[60];

 8 int ans, n;

 9 

10 void dfs(int pos, int num)

11 {

12      if(num==n)

13      {

14          ans++;

15          return ;

16      }

17      for(int i=pos-2; i<=pos+2&&i<=n; i++)

18      {

19          if(i<=1) continue;

20          if(!color[i])

21          {

22              color[i]=1;

23              dfs(i,num+1);

24              color[i]=0;

25          }

26      }

27 }

28 int main()

29 {

30     while(scanf("%d",&n)!=EOF)

31     {

32         memset(color,0,sizeof(color));

33         ans=0;

34         color[1]=1;

35         dfs(1,1);

36         printf("%d\n",ans);

37     }

38     return 0;

39 }

 

AC代码

 1 #include <iostream>

 2 #include <cstdio>

 3 #include <algorithm>

 4 #include <cstring>

 5 using namespace std;

 6 

 7 int main()

 8 {

 9     int  n, dp[60];

10     dp[1]=1, dp[2]=1, dp[3]=2, dp[4]=4;

11     for(int i=5; i<=55; i++)

12         dp[i]=dp[i-1]+dp[i-3]+1;

13     while(scanf("%d",&n)!=EOF)

14     {

15         printf("%d\n",dp[n]);

16     }

17     return 0;

18 }

 

 

你可能感兴趣的:(DFS)