K - Binary Indexed Tree HDU - 5921 (数位dp)

#include<stdio.h>
#include<string.h>
#define ll long long
ll w[150],q[150],dp[150][2][2][2];
#define mod 1000000007
ll getans(int pos,int flaga,int flagb){
	if(pos<0)return 1;
	ll ans=1;
	if(flaga==1)ans=(ans*q[pos])%mod;
	else ans=(ans*((1ll<<(pos+1))%mod))%mod;
	if(flagb==1)ans=(ans*q[pos])%mod;
	else ans=(ans*((1ll<<(pos+1))%mod))%mod;
	return ans;
}
ll dfs(int pos,int flaga,int flagb,int flag){
	if(pos<0)return 0;
	if(dp[pos][flaga][flagb][flag]!=-1)return dp[pos][flaga][flagb][flag];
	int maxa=1,maxb=1;
	if(flaga==1)maxa=w[pos];
	if(flagb==1)maxb=w[pos];
	ll ans=0;
	for(int i=0;i<=maxa;i++){
		for(int j=0;j<=maxb;j++){
			ans=(ans+dfs(pos-1,flaga&(i==maxa),flagb&(j==maxb),flag|(i!=j)))%mod;
			ans=(ans+(flag|(i!=j))*(i+j)*getans(pos-1,flaga&(i==maxa),flagb&(j==maxb)))%mod;
		}
	}
	dp[pos][flaga][flagb][flag]=ans;
	return ans;
}
ll solve(ll n){
	int cnt=0;
	while(n!=0){
		w[cnt++]=n%2;
		n=n/2;
	}
	q[0]=w[0];
	for(int i=1;i<cnt;i++){
		q[i]=(q[i-1]+(w[i]<<i))%mod;
	}
	for(int i=0;i<cnt;i++){
		q[i]++;
	}
	return dfs(cnt-1,1,1,0);
}
int main(){
	int t;
	scanf("%d",&t);
	int cas=0;
	while(t--){
		memset(dp,-1,sizeof(dp));
		ll n;
		scanf("%lld",&n);
		ll temp=(mod+1)/2;
		ll ans=solve(n)*temp%mod;
		printf("Case #%d: %lld\n",++cas,ans);
	}
}
上一篇:Medium | LeetCode 150. 逆波兰表达式求值 | 栈


下一篇:利用Gurobi求解线性整数规划问题(Python)