Let’s call a list of positive integers a0,a1,…,an−1 a power sequence if there is a positive integer c, so that for every 0≤i≤n−1 then ai=ci.
Given a list of n positive integers a0,a1,…,an−1, you are allowed to:
Reorder the list (i.e. pick a permutation p of {0,1,…,n−1} and change ai to api), then
Do the following operation any number of times: pick an index i and change ai to ai−1 or ai+1 (i.e. increment or decrement ai by 1) with a cost of 1.
Find the minimum cost to transform a0,a1,…,an−1 into a power sequence.
Input
The first line contains an integer n (3≤n≤105).
The second line contains n integers a0,a1,…,an−1 (1≤ai≤109).
Output
Print the minimum cost to transform a0,a1,…,an−1 into a power sequence.
#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int maxn = 1e5+3;
ll a[maxn];
int main()
{
ios::sync_with_stdio(false);
int n,m=1;
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
sort(a+1,a+n+1);
ll res=1e18;
for(ll c=1;;c++)
{
ll sum=0,now=1;
for(ll i=1;i<=n;i++)
{
sum+=abs(a[i]-now);
now*=c;
if(now>=1e15)
{
now=-1;
break;
}
}
if(now==-1)
{
break;
}
else
{
res=min(res,sum);
}
}
cout<<res<<endl;
}
非常重要的一个地方就是,now可以放在循环里,不用在浪费复杂度单独计算了