CodeForces 8 E.Beads(数位DP)

Description

定义一个 n n 01串和其翻转后得到的串(翻转指的是把 1 1 变成0,把 0 0 变成1),其反串以及其反串翻转得到的串等价,且该等价类的代表元选取这四个串中字典序最小的串,求所有代表元中字典序第 k k 小的串

Input

两个整数n,k(2n50,1k1016)

Output

如果存在不少于 k k 个代表元则输出其中字典序第k小的,否则输出 1 − 1

Sample Input

4 4

Sample Output

0101

Solution

由定义,代表元为字典序不超过其反串,其翻转串以及其反串的翻转串,设其最低位为第 1 1 位,最高位为第n位,显然该串的第 n n 位为0,从最高位到最低位开始一位位确定答案,假设从第 n n 位到第i+1位全部确定,记为 a[n],...,a[i+1] a [ n ] , . . . , a [ i + 1 ] ,当前步确定第 i i 位,假设第i位是 0 0 ,那么我们要求出满足从第i位到最高位确定的合法串数量,用数位 DP D P 解决该问题,以 dp[pos][x][y] d p [ p o s ] [ x ] [ y ] 表示满足第 pos+1 p o s + 1 位到第 n n 位确定,n~ pos+1 p o s + 1 位的字典序不超过 1 1 ~npos位,同时也不超过 1 1 ~npos位的翻转,状态为 x,y x , y 01 01 串数量,其中 x x 表示n~ pos+1 p o s + 1 位与 1 1 ~npos位是否相同, y y 表示n~ pos+1 p o s + 1 位与 1 1 ~npos位的翻转是否相同,当前步目的是确定第 pos p o s 位和第 npos+1 n − p o s + 1 位的同时计数,枚举这两位的取值分别为 i,j i , j ,那么如果 x=1 x = 1 ,即 n n ~pos+1位与 1 1 ~npos位相同,那么 i i 不能超过j,否则 n n ~pos位的字典序会超过 1 1 ~npos+1位的字典序,不合法;如果 y=1 y = 1 ,即 n n ~pos+1位与 1 1 ~npos位的翻转相同,那么 i i 不能超过j的翻转 !j ! j ,否则 n n ~pos位的字典序会超过 1 1 ~npos+1位翻转后的字典序,不合法;如果 pos=npos+1 p o s = n − p o s + 1 ,说明这两位重复,那么 i,j i , j 应该相同,否则显然冲突, i,j i , j 若合法则有转移:

dp[pos][x][y]+=dp[pos1][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 说明第i位确实应该取 0 0 ,否则说明第i位取 1 1 k也需要减掉 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值