USACO 5.4 Twofive(DP)

时间:2024-01-04 17:27:32

非常不容易的一题,思路就是DP之后输出路径。但是此题,路径和DP的方式不一样,路径要按字典序输出。

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

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

USACO 5.4 Twofive(DP)

 /*
ID: cuizhe
LANG: C++
TASK: twofive
*/
#include <cstdio>
#include <cstring>
using namespace std;
char str[];
char te[];
int dp[][][][][];
int judge(int x,int step)
{
if(!te[x]||te[x] == step + 'A')
return ;
else
return ;
}
int dfs(int x1,int x2,int x3,int x4,int x5,int step)
{
int ans = ;
if(step == )
return ;
if(dp[x1][x2][x3][x4][x5])
return dp[x1][x2][x3][x4][x5];
if(x1 < &&judge(x1,step))
ans += dfs(x1+,x2,x3,x4,x5,step+);
if(x2 < x1&&judge(x2+,step))
ans += dfs(x1,x2+,x3,x4,x5,step+);
if(x3 < x2&&judge(x3+,step))
ans += dfs(x1,x2,x3+,x4,x5,step+);
if(x4 < x3&&judge(x4+,step))
ans += dfs(x1,x2,x3,x4+,x5,step+);
if(x5 < x4&&judge(x5+,step))
ans += dfs(x1,x2,x3,x4,x5+,step+);
return dp[x1][x2][x3][x4][x5] = ans;
}
int main()
{
char ch[];
freopen("twofive.in","r",stdin);
freopen("twofive.out","w",stdout);
int n,i,temp,ans;
scanf("%s",ch);
if(ch[] == 'N')
{
scanf("%d",&n);
for(i = ;i < ;i ++)
{
for(te[i] = 'A';;te[i] ++)
{
memset(dp,,sizeof(dp));
if((temp = dfs(,,,,,)) < n)
n -= temp;
else
break;
}
}
te[] = '\0';
printf("%s\n",te);
}
else
{
scanf("%s",str);
for(i = ;i < ;i ++)
{
for(te[i] = 'A';te[i] < str[i];te[i] ++)
{
memset(dp,,sizeof(dp));
ans += dfs(,,,,,);
}
}
printf("%d\n",ans+);
}
return ;
}