Description
定义一个 n n 位串和其翻转后得到的串(翻转指的是把 1 1 变成,把 0 0 变成),其反串以及其反串翻转得到的串等价,且该等价类的代表元选取这四个串中字典序最小的串,求所有代表元中字典序第 k k 小的串
Input
两个整数
Output
如果存在不少于 k k 个代表元则输出其中字典序第小的,否则输出 −1 − 1
Sample Input
4 4
Sample Output
0101
Solution
由定义,代表元为字典序不超过其反串,其翻转串以及其反串的翻转串,设其最低位为第 1 1 位,最高位为第位,显然该串的第 n n 位为,从最高位到最低位开始一位位确定答案,假设从第 n n 位到第位全部确定,记为 a[n],...,a[i+1] a [ n ] , . . . , a [ i + 1 ] ,当前步确定第 i i 位,假设第位是 0 0 ,那么我们要求出满足从第位到最高位确定的合法串数量,用数位 DP D P 解决该问题,以 dp[pos][x][y] d p [ p o s ] [ x ] [ y ] 表示满足第 pos+1 p o s + 1 位到第 n n 位确定,~ pos+1 p o s + 1 位的字典序不超过 1 1 ~位,同时也不超过 1 1 ~位的翻转,状态为 x,y x , y 的 01 01 串数量,其中 x x 表示~ pos+1 p o s + 1 位与 1 1 ~位是否相同, y y 表示~ pos+1 p o s + 1 位与 1 1 ~位的翻转是否相同,当前步目的是确定第 pos p o s 位和第 n−pos+1 n − p o s + 1 位的同时计数,枚举这两位的取值分别为 i,j i , j ,那么如果 x=1 x = 1 ,即 n n ~位与 1 1 ~位相同,那么 i i 不能超过,否则 n n ~位的字典序会超过 1 1 ~位的字典序,不合法;如果 y=1 y = 1 ,即 n n ~位与 1 1 ~位的翻转相同,那么 i i 不能超过的翻转 !j ! j ,否则 n n ~位的字典序会超过 1 1 ~位翻转后的字典序,不合法;如果 pos=n−pos+1 p o s = n − p o s + 1 ,说明这两位重复,那么 i,j i , j 应该相同,否则显然冲突, i,j i , j 若合法则有转移:
dp[pos][x][y]+=dp[pos−1][x&&(i==j)][y&&(i!=j)] d p [ p o s ] [ x ] [ y ] + = d p [ p o s − 1 ] [ x & & ( i == j ) ] [ y & & ( i ! = j ) ]
以此求出 dp[n][1][1] d p [ n ] [ 1 ] [ 1 ] 即为所求,如果该值不小于 k k 说明第位确实应该取 0 0 ,否则说明第位取 1 1 ,也需要减掉 dp[n][1][1] d p [ n ] [ 1 ] [ 1 ] ,以此类推一位位确定答案即可
Code
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<queue>
#include<map>
#include<set>
#include<ctime>
using namespace std;
typedef long long ll;
typedef pair<int,int>P;
const int INF=0x3f3f3f3f,maxn=55;
int n,a[maxn];
ll dp[maxn][2][2],k;
ll dfs(int pos,int x,int y)
{
if(pos<n-pos+1)return 1;
if(dp[pos][x][y]!=-1)return dp[pos][x][y];
ll ans=0;
for(int i=0;i<=1;i++)
if(a[pos]==-1||a[pos]==i)
for(int j=0;j<=1;j++)
if(a[n-pos+1]==-1||a[n-pos+1]==j)
{
if(x&&(i>j)||y&&(i>!j)||pos==n-pos+1&&(i!=j))continue;
ans+=dfs(pos-1,x&&(i==j),y&&(i!=j));
}
return dp[pos][x][y]=ans;
}
int main()
{
scanf("%d%I64d",&n,&k);
k++;
memset(a,-1,sizeof(a));
memset(dp,-1,sizeof(dp));
a[n]=0;
if(dfs(n,1,1)<k)printf("-1\n");
else
{
for(int i=n-1;i>=1;i--)
{
a[i]=0;
memset(dp,-1,sizeof(dp));
ll num=dfs(n,1,1);
if(k>num)k-=num,a[i]=1;
}
for(int i=n;i>=1;i--)printf("%d",a[i]);
printf("\n");
}
return 0;
}