AtCoder Beginner Contest 340C - Divide and Divide

problem link

Naively, a brute force recursion solution be implemented with O ( n ) \mathcal O (n) O(n) complexity.

复制代码
int work(int x)
{
	if(x==1)return 0;
	return x+work(x>>1)+work((x>>1)+(x&1))
}

However, since all possible x x x can be represented as n ⋅ 2 − k + [ 0 / 1 ] n\cdot 2^{-k}+[0/1] n⋅2−k+[0/1], the number of possible x x x does not exceed 2 ⋅ log ⁡ 2 ( n ) 2\cdot \log_2(n) 2⋅log2(n)

Then, we can intuitively implement a memorization search with map.

cpp 复制代码
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<map>
using namespace std;
map <long long,long long> f;
long long n,ans;
long long work(long long x)
{
	if(x==1)return 0;
	if(f[x])return f[x];
	return f[x]=x+work(x>>1)+work((x>>1)+(x&1));
}
int main()
{
	cin>>n;
	cout<<work(n)<<endl;
	return 0;
}
相关推荐
嘉陵妹妹11 分钟前
深度优先算法学习
学习·算法·深度优先
GalaxyPokemon40 分钟前
LeetCode - 53. 最大子数组和
算法·leetcode·职场和发展
hn小菜鸡1 小时前
LeetCode 1356.根据数字二进制下1的数目排序
数据结构·算法·leetcode
zhuiQiuMX1 小时前
分享今天做的力扣SQL题
sql·算法·leetcode
music&movie3 小时前
算法工程师认知水平要求总结
人工智能·算法
laocui13 小时前
Σ∆ 数字滤波
人工智能·算法
yzx9910134 小时前
Linux 系统中的算法技巧与性能优化
linux·算法·性能优化
全栈凯哥4 小时前
Java详解LeetCode 热题 100(26):LeetCode 142. 环形链表 II(Linked List Cycle II)详解
java·算法·leetcode·链表
全栈凯哥4 小时前
Java详解LeetCode 热题 100(27):LeetCode 21. 合并两个有序链表(Merge Two Sorted Lists)详解
java·算法·leetcode·链表
SuperCandyXu4 小时前
leetcode2368. 受限条件下可到达节点的数目-medium
数据结构·c++·算法·leetcode