C. Sum of Log(数位dp)

C. Sum of Log

Code1

暴力记的状态 TLE

#include<bits/stdc++.h>
using namespace std;
using ll=long long;
template <class T=int> T rd()
{
    T res=0;T fg=1;
    char ch=getchar();
    while(!isdigit(ch)) {if(ch=='-') fg=-1;ch=getchar();}
    while( isdigit(ch)) res=(res<<1)+(res<<3)+(ch^48),ch=getchar();
    return res*fg;
}
const ll mod=1e9+7;
int a[33],b[33];
int f[33][33][2][2];
int dfs(int u,int m,int lim1,int lim2)
{
    if(!u) return (m);
    if(f[u][m][lim1][lim2]!=-1) return f[u][m][lim1][lim2];
    f[u][m][lim1][lim2]=0;
    int v1=lim1?a[u]:1;
    int v2=lim2?b[u]:1;
    int ans=0;
    for(int i=0;i<=v1;i++)
        for(int j=0;j<=v2;j++)
            if(!(i&j))
            {
                int cur=m;
                if(i==1||j==1) cur=max(m,u);
                ans=(1ll*ans+dfs(u-1,cur,lim1&&(i==a[u]),lim2&&(j==b[u])))%mod;
            }
    return f[u][m][lim1][lim2]=ans;
}
int solve(int x,int y)
{

    int m=0;
    while(x||y)
    {
        a[++m]=(x&1);
        b[m]=(y&1);
        x>>=1;
        y>>=1;
    }
    for(int i=0;i<=m;i++) for(int j=0;j<=m;j++) 
    for(int p=0;p<=1;p++) for(int q=0;q<=1;q++) f[i][j][p][q]=-1;
    return dfs(m,0,1,1);
}
int main()
{
    int Tc=rd();
    while(Tc--)
    {
        int x=rd(),y=rd();
        printf("%d\n",solve(x,y));
    }
    
    return 0;
}
Code2

稍微优化了一下 AC

#include<bits/stdc++.h>
#pragma GCC optimize(2)

using namespace std;
using ll=long long;
template <class T=int> T rd()
{
    T res=0;T fg=1;
    char ch=getchar();
    while(!isdigit(ch)) {if(ch=='-') fg=-1;ch=getchar();}
    while( isdigit(ch)) res=(res<<1)+(res<<3)+(ch^48),ch=getchar();
    return res*fg;
}
const int mod=1e9+7;
int a[33],b[33];
int f[33][2][2][2];
int dfs(int u,int m,int lim1,int lim2)
{
    if(!u) return (1);
    if(f[u][m][lim1][lim2]!=-1) return f[u][m][lim1][lim2];
    
    int v1=lim1?a[u]:1;
    int v2=lim2?b[u]:1;
    int ans=0;
    for(int i=0;i<=v1;i++)
        for(int j=0;j<=v2;j++)
            if(!(i&j))
            {
                int c=1;
                if(m==0&&(i==1||j==1)) c=u;
                
                ans=(1ll*c*dfs(u-1,m||i==1||j==1,lim1&&(i==a[u]),lim2&&(j==b[u]))%mod+ans)%mod;
            }
    return f[u][m][lim1][lim2]=ans;
}
int solve(int x,int y)
{

    int m=0;
    while(x||y)
    {
        a[++m]=(x&1);
        b[m]=(y&1);
        x>>=1;
        y>>=1;
    }
    memset(f,-1,sizeof f);
    
    return dfs(m,0,1,1);
}
int main()
{
    int Tc=rd();
    while(Tc--)
    {
        int x=rd(),y=rd();
        printf("%d\n",(solve(x,y)-1+mod)%mod);
    }
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值