LightOJ - 1032 Fast Bit Calculations(数位dp)

题目链接:点击这里

题目大意:
给定一个正整数 n n n ,求 [ 0 , n ] [0,n] [0,n] 中有多少个二进制相邻位是1的总数

题目分析:
数位 d p dp dp
定义状态 d p [ i ] [ j ] [ k ] dp[i][j][k] dp[i][j][k] 为前 i i i 位上一位是 j j j ,前 i − 1 i-1 i1 位和为 k k k 的数中二进制相邻位是1的总数
按照数位 d p dp dp 转移,转移时维护上一位,和上一位的答案即可
之所以要维护上一位的答案来作为下一位的状态,是因为不记录的话会有很多答案不同的状态被一同表示,例如如果删掉第三维 0111 0111 0111 d p [ 2 ] [ 1 ] = 1 dp[2][1] = 1 dp[2][1]=1 ,但是 1111 1111 1111 d p [ 2 ] [ 1 ] = 2 dp[2][1]=2 dp[2][1]=2 ,如果直接记忆化就会产生答案贡献错误的问题;而如果前面贡献相同, d p [ i ] [ j ] dp[i][j] dp[i][j] 才会相同,所以要加上一维前 i − 1 i-1 i1 位的和

具体细节见代码:

//#pragma GCC optimize(2)
//#pragma GCC optimize("Ofast","inline","-ffast-math")
//#pragma GCC target("avx,sse2,sse3,sse4,mmx")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<vector>
#include<set>
#include<map>
#include<stack>
#include<queue>
#define ll long long
#define inf 0x3f3f3f3f
#define int  ll
#define endl '\n'
#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0)
using namespace std;
int read()
{
	int res = 0,flag = 1;
	char ch = getchar();
	while(ch<'0' || ch>'9')
	{
		if(ch == '-') flag = -1;
		ch = getchar();
	}
	while(ch>='0' && ch<='9')
	{
		res = (res<<3)+(res<<1)+(ch^48);//res*10+ch-'0';
		ch = getchar();
	}
	return res*flag;
}
const int maxn = 55+5;
const int mod = 998244353;
const double pi = acos(-1);
const double eps = 1e-8;
int n,a[maxn],dp[maxn][2][maxn];
int dfs(int pos,int pre,int sum,bool f1)
{
	if(pos == -1) return sum;
	if(!f1 && dp[pos][pre][sum] != -1) return dp[pos][pre][sum];
	int up = f1 ? a[pos] : 1,res = 0;
	for(int i = 0;i <= up;i++)
		res += dfs(pos-1,i&1,sum+(pre&i),f1&&i==up);
	if(!f1) dp[pos][pre][sum] = res;
	return res;
} 
int calc(int x)
{
	int cnt = 0;
	while(x)
	{
		a[cnt++] = x&1;
		x >>= 1;
	}
	return dfs(cnt-1,0,0,1);
}
signed main()
{
	memset(dp,-1,sizeof(dp));
	int t = read();
	for(int i = 1;i <= t;i++)
	{
		n = read();
		cout<<"Case "<<i<<": "<<calc(n)<<endl;
	}
	return 0;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值