Time Limits: 1000 ms Memory Limits: 131072 KB Special Judge
Description
Input
Output
Sample Input
2 2
ab
Sample Output
5
abbaa
Data Constraint
Solution
构造答案
先考虑如何构造可以使得长度最短,
设想一种最优的方案,
每添加一个字符,
都可以与当前已构造完毕的字符串的后
l−1
l
−
1
个构成一个新的长度为l的字符串,
那么最终长度就是
cl+l−1
c
l
+
l
−
1
。
可是怎样才会出现这种最优情况呢?
我们将每个长度为
l−1
l
−
1
的字符串看成一个点,
从一个字符串转换到另一个字符串只需要新增一个字符,
在转换的过程中我们考虑用c进制数表示每个字符串,
由于每个点都可以向外连出c条边,
最终就是问题转化为求一条欧拉回路。
Code
#include<algorithm>
#include<cstdio>
#include<stack>
#define N 1024*1024*10
using namespace std;
int c,l,k,top,b[30],d[N];
short int use[N],cnt[N],ans[N];
char s[30];
void solve()
{
d[top=1]=0;
while(top)
{
int x=d[top];
if(cnt[x]<c)
{
use[++top]=++cnt[x];
d[top]=x%b[l-2]*c+cnt[x]-1;
}
else if(top>1) ans[++k]=use[top--]; else break;
}
}
int main()
{
freopen("life.in","r",stdin);
freopen("life.out","w",stdout);
scanf("%d%d",&c,&l);
scanf("%s",s);
b[0]=1;
for(int i=1;i<=l;i++) b[i]=b[i-1]*c;
printf("%d\n",b[l]+l-1);
if(l==1)
{
printf("%s",s);
return 0;
}
for(int i=1;i<l;i++) putchar(s[0]);
solve();
for(int i=k;i;i--) putchar(s[ans[i]-1]);
}