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.
Examples
inputCopy
3
1 3 2
outputCopy
1
inputCopy
3
1000000000 1000000000 1000000000
outputCopy
1999982505
Note
In the first example, we first reorder {1,3,2} into {1,2,3}, then increment a2 to 4 with cost 1 to get a power sequence {1,2,4}.
题意:给你一个整数序列,然后你排好序后,可以执行的操作为将数列某个数加1或减1,问最少经过多少次操作,可以使序列变成幂数序列。满足a[i]=c^i。
思路:这题最基本的思路就是枚举,枚举c的大小。由题目范围可知n最少取3,那么我们可以得出c最大取31623,因为31623的平方已超过1e9。所以在这个范围内枚举c即可。找出最小的c使得 pow(c,n-1)>=a[n-1] 即可。得出这个c之后我们还要考虑一下c-1的情况,因为不确定连个幂数哪一个会使操作次数更少。
#include<bits/stdc++.h>
#define ll long long
#define inf 1e15
using namespace std;
int main()
{
ll t,n,a[100005];
cin>>n;
for(int i=0;i<n;i++)
cin>>a[i];
sort(a,a+n);
int u;
for(int i=1;i<=31623;i++)
{
if(pow(i,n-1)>=a[n-1])
{
u=i;
break;
}
}
ll sum1=0,sum2=0,sum1f=0,sum2f=0;
if(u>1)
{
int v=u-1;
for(int i=0;i<n;i++)
{
sum1+=abs(a[i]-pow(u,i));
if(sum1>=inf) //考虑到可能会特别大成为一个负数,就会影响后面的 min(sum1,sum2) ,因加一个判断条件,是负数的话就不会输出
{
sum1f=1;
}
sum2+=abs(a[i]-pow(v,i));
if(sum2>=inf) //同上
{
sum2f=1;
}
}
if(sum1f==1) //只要有一方出现了负数,那就输出另一方即可
cout<<sum2<<endl;
else if(sum2f==1)
cout<<sum1<<endl;
else
cout<<min(sum1,sum2)<<endl;
}
else
{
for(int i=0;i<n;i++)
{
sum1+=abs(a[i]-pow(u,i));
}
cout<<sum1<<endl;
}
}