Question meaning:
N count
You can divide it into multiple segments. The length of each segment cannot exceed 20.
Yes, sum (ai * (2 ^ bi) is the smallest. ai is the first number in each segment, and bi is the length.
Solution:
Set dp [I] = min (dp [I], dp [j] + a [I] * 2 ^ (j-I), 1 <= I <= n, I + 1 <= j <= min (I + 20, n + 1)
Dp [I] indicates the value starting with I
Finally, we will compare dp [1] with a comparison into n segments.
There are a lot of code on the Internet. I wrote an iteration, which is faster than the memory-based search.
#include<cstdio> #include<cstring> #include<cmath> #include<algorithm> #include<iostream> using namespace std; #define ULL long long const int maxn = 65; ULL dp[maxn]; ULL a[maxn]; int n; int main() { int t; scanf("%d",&t); while(t--) { scanf("%d",&n); ULL ans=0; for(int i=1;i<=n;i++) { cin>>a[i]; ans += a[i]*2; } dp[n] = a[n]*2; dp[n+1] = 0; for(int i=n-1;i>=1;i--) { dp[i] = (1ULL<<62-1); for(int j=i+1;j<=min(i+20,n+1);j++) { dp[i] = min(dp[i],dp[j]+a[i]*(1<<(j-i))); } } cout<<min(ans,dp[1])<<endl; } return 0; }