您的位置:首页 > 其它

USACO5.5.3 (twofive)

2015-02-05 18:15 183 查看
矩阵转编号:

如矩阵ACEGI......

只需求出以AB、ACD、ACEF、ACEFH......开头的矩阵的数目之和再加1即可。

编号转矩阵:

顺次枚举每一位,若当前方案开头的矩阵数目小于n则减去,否则即可确定当前位。

记忆化搜索,求以固定串开头的矩阵数目。

令f[a][b][c][d][e]表示各行分别放入了a,b,c,d,e个字符的方案数。

则合法状态中,必然五参数不严格递减。

从小往大枚举每一字符,选择放到哪一行中,且必然放在该行接下来的一格中。

/*
ID:xsy97051
LANG:C++
TASK:twofive
*/
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;

#define 25 25

char c,t[25+9];
bool mark[128];
int f[6][6][6][6][6];

#define ok(x) (!t[x] || t[x]==deep+'A')

int dfs(int a,int b,int c,int d,int e,int deep)
{
if(deep==25)	return 1;
int &now=f[a][b][c][d][e];
if(now)	return now;
if(a<5 && ok(a))		now+=dfs(a+1,b,c,d,e,deep+1);
if(b<a && ok(b+5))		now+=dfs(a,b+1,c,d,e,deep+1);
if(c<b && ok(c+10))		now+=dfs(a,b,c+1,d,e,deep+1);
if(d<c && ok(d+15))		now+=dfs(a,b,c,d+1,e,deep+1);
if(e<d && ok(e+20))		now+=dfs(a,b,c,d,e+1,deep+1);
return now;
}/*
求出以某给定序列开头的单词的个数,用记忆化搜索解决的。
用f[a,b, c,d,e](5>=a>=b>=c>=d>=e>=0)表示把前a+b+c+d+e个字母填入
第1行的前a个格,第2行的前b个格……第5行的前e个格,
且已经确定位置的字母各就各位时可能的单词数,f[0,0,0,0,0]就表示以给定序列开头的单词数。
*/
void do_N()
{
int n,tmp;
cin>>n;
for(int i=0;i<25;++i)
for(t[i]='A';memset(f,0,sizeof(f)),(tmp=dfs(0,0,0,0,0,0))<n;++t[i])
n-=tmp;

for(int i=0;i<25;i++)
cout<<t[i];
cout<<endl;
}

void do_W()
{
int ans=0;
string s;
cin>>s;
for(int i=0;i<25;++i)
for(t[i]='A';t[i]<s[i];++t[i])
{
memset(f,0,sizeof(f));
ans+=dfs(0,0,0,0,0,0);
}
cout<<ans+1<<endl;
}

int main()
{
freopen("twofive.in","r",stdin);
freopen("twofive.out","w",stdout);
char cc;
cin>>cc;

if( cc=='N' ) do_N();
else do_W();

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