【URAL 1260】 DP (dfs打表之后找规律也行)
2012-11-07 15:55
260 查看
题目链接:http://acm.timus.ru/problem.aspx?space=1&num=1260
题目大意:有n个数1—n,将他们排成一列。最左边必须是1,后面排列的数字和与他们它们相邻的数字只差不能超过2,求有多少中排列方式。
解题思路:
一开始看到这题,才55个点,果断dfs,结果TLE。不过至少答案是正确的,然后把答案给记录起来,仔细一分析,发现有规律可寻,打表,果断过了。
规律递推式:dp
=dp[n-1]+dp[n-3]+1。
搜狗一下发现别人此题写的是DP,囧。
然后又思考了一下,果然如此。
n个人时求dp
。第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超时代码
AC代码
题目大意:有n个数1—n,将他们排成一列。最左边必须是1,后面排列的数字和与他们它们相邻的数字只差不能超过2,求有多少中排列方式。
解题思路:
一开始看到这题,才55个点,果断dfs,结果TLE。不过至少答案是正确的,然后把答案给记录起来,仔细一分析,发现有规律可寻,打表,果断过了。
规律递推式:dp
=dp[n-1]+dp[n-3]+1。
搜狗一下发现别人此题写的是DP,囧。
然后又思考了一下,果然如此。
n个人时求dp
。第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超时代码
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; int color[60]; int ans, n; void dfs(int pos, int num) { if(num==n) { ans++; return ; } for(int i=pos-2; i<=pos+2&&i<=n; i++) { if(i<=1) continue; if(!color[i]) { color[i]=1; dfs(i,num+1); color[i]=0; } } } int main() { while(scanf("%d",&n)!=EOF) { memset(color,0,sizeof(color)); ans=0; color[1]=1; dfs(1,1); printf("%d\n",ans); } return 0; }
AC代码
#include <iostream> #include <cstdio> #include <algorithm> #include <cstring> using namespace std; int main() { int n, dp[60]; dp[1]=1, dp[2]=1, dp[3]=2, dp[4]=4; for(int i=5; i<=55; i++) dp[i]=dp[i-1]+dp[i-3]+1; while(scanf("%d",&n)!=EOF) { printf("%d\n",dp ); } return 0; }
相关文章推荐
- Ural 1260 A nudnik photographer(DP)
- HDU 4588 Count The Carries 数位DP || 打表找规律
- ural 1260. Nudnik Photographer(dp)
- 2016 大连 K Guess the number HDU 5981 DP 打表找规律
- 记忆化搜索(DFS+DP) URAL 1501 Sense of Beauty
- 【BZOJ3227】红黑树,打表找规律/DP
- ural 1056 Computer Net(树形DP)需要用到两遍dfs
- 递推DP URAL 1260 Nudnik Photographer
- Ural 2037. Richness of binary words 打表找规律 构造
- Ural_1260. Nudnik Photographer(DP)
- Ural 1260. A nudnik photographer(dp)
- URAL——DFS找规律——Nudnik Photographer
- ural&nbsp;1260(找规律)
- ural1009 第一个动态规划(dp)题目 。。。似乎也可以用dfs+记忆化收索 解。。。
- 记忆化搜索(DP+DFS) URAL 1183 Brackets Sequence
- Ural 2045. Richness of words 打表找规律
- ural 1171 DFS+DP
- 【算法设计与数据结构】URAL 1152.False Mirrors(状态压缩dp+dfs)
- ural 1005 dp dfs or 0 1背包
- hdu 1028 Ignatius and the Princess III(打表,后期进阶补->找规律和dp)