您的位置:首页 > 其它

USACO 5.4 Twofive(DP)

2013-08-26 10:46 330 查看
非常不容易的一题,思路就是DP之后输出路径。但是此题,路径和DP的方式不一样,路径要按字典序输出。

开始写了一个版本,N 10000的时候就是过不了,后来才发现,自己的写法有问题,无法保证字典序。看了看题解,其实也不是很懂。

终于还有3个题,加油了!!



/*
ID: cuizhe
LANG: C++
TASK: twofive
*/
#include <cstdio>
#include <cstring>
using namespace std;
char str[101];
char te[101];
int dp[6][6][6][6][6];
int judge(int x,int step)
{
if(!te[x]||te[x] == step + 'A')
return 1;
else
return 0;
}
int dfs(int x1,int x2,int x3,int x4,int x5,int step)
{
int ans = 0;
if(step == 25)
return 1;
if(dp[x1][x2][x3][x4][x5])
return dp[x1][x2][x3][x4][x5];
if(x1 < 5&&judge(x1,step))
ans += dfs(x1+1,x2,x3,x4,x5,step+1);
if(x2 < x1&&judge(x2+5,step))
ans += dfs(x1,x2+1,x3,x4,x5,step+1);
if(x3 < x2&&judge(x3+10,step))
ans += dfs(x1,x2,x3+1,x4,x5,step+1);
if(x4 < x3&&judge(x4+15,step))
ans += dfs(x1,x2,x3,x4+1,x5,step+1);
if(x5 < x4&&judge(x5+20,step))
ans += dfs(x1,x2,x3,x4,x5+1,step+1);
return dp[x1][x2][x3][x4][x5] = ans;
}
int main()
{
char ch[10];
freopen("twofive.in","r",stdin);
freopen("twofive.out","w",stdout);
int n,i,temp,ans;
scanf("%s",ch);
if(ch[0] == 'N')
{
scanf("%d",&n);
for(i = 0;i < 25;i ++)
{
for(te[i] = 'A';;te[i] ++)
{
memset(dp,0,sizeof(dp));
if((temp = dfs(0,0,0,0,0,0)) < n)
n -= temp;
else
break;
}
}
te[25] = '\0';
printf("%s\n",te);
}
else
{
scanf("%s",str);
for(i = 0;i < 25;i ++)
{
for(te[i] = 'A';te[i] < str[i];te[i] ++)
{
memset(dp,0,sizeof(dp));
ans += dfs(0,0,0,0,0,0);
}
}
printf("%d\n",ans+1);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: