您的位置:首页 > 其它

【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超时代码

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: