链接:https://ac.nowcoder.com/acm/contest/940/A
kotori共有n块糖果,每块糖果的初始状态是分散的,她想把这些糖果聚在一堆。但她每次只能把两堆糖果合并成一堆。
已知把两堆数量为a和b的糖果聚在一堆的代价是|a-b|。
kotori想知道,她把这n块糖果聚在一堆的最小代价是多少?
解:OEIS搜索序列前12个数,出来唯一一的结果,该序列介绍中有如下这一条:
the minimum cost of connecting n+1 nodes when the cost of joining two connected components is the absolute difference of their sizes. In particular, connecting two equal sized components has zero cost. For example, in the case of n=4 there are 5 nodes. Connecting nodes 1 and 2 costs zero, connecting nodes 3 and 4 costs zero, then connecting {5} to {3,4} costs 1 and finally connecting {1,2} to {3,4,5} costs 1 giving a total cost of 2. Because this solution is optimal a(4) = 2.
正符合题意!
序列的计算式 formula :a(0) = a(1) = 0; a(2*n) = a(n) + a(n-1) + 1; a(2*n+1) = 2*a(n)
写出这个递归就好啦。
数比较大,用map存。
然后递归写挂了(不
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
map<ll,ll> mp;
ll getans(ll n){
if(n==0) return 0;
if(mp.count(n)) return mp[n];
if(n&1){
mp[n]=2*getans(n/2);
}else{
mp[n]=getans(n/2)+getans(n/2-1)+1;
}
return mp[n];
}
int main(){
ll t;
scanf("%lld",&t);
while(t--){
ll n;
scanf("%lld",&n);
if(n==0)puts("0");
else printf("%lld\n",getans(n-1));
}
}