题目
传送门
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.
输入
3
1 3 2
输出
1
输入
3
1000000000 1000000000 1000000000
输出
1999982505
题意:给你一个序列,你可以对序列任意排列,然后你可以对序列中的任意元素进行一步操作:对任意元素进行加一,减一.问:你想让序列a0~an-1分别对应一个整数C的0-(n-1)次方,需要的最小操作数是多少?
思路:我们把序列从小到大排序,当n为1时,那个数一定对应的C的0次方,此时答案为a[0]-1,n=2时,我们选c=a[1],那么操作数还是a[0]-1,对于更大的数我们可以直接暴力反正范围只有1e9,2的32次方就可以,C更大时次数更少,具体看代码
AC code
#include<iostream>
#include<algorithm>
#include<cstring>
#include<map>
#include<cmath>
#include<queue>
#include<sstream>
#include<vector>
using namespace std;
#define ll long long
const ll inf=1e18;
ll a[120000],n;
void solve()
{
ll s=0,ss=0;
cin>>n;
for(int i=0;i<n;i++)
{cin>>a[i];
ss+=a[i];}
sort(a,a+n);
if(n>=53)
printf("%lld\n",ss-n);
else
{
if(n==1||n==2)
printf("%d\n",a[0]-1);
else
{
ll maxx=inf,flag=1,oo=0;
for(ll i=2;i<=100000;i++)
{
ll q=0,tt=1;
for(ll j=0;j<n;j++)
{
if(tt>1e14)
{
flag=0;
break;
}
q+=abs(a[j]-tt);
tt*=i;
}
if(flag==0)break;
if(maxx>q)
{
oo=i;
maxx=q;
}
}
ll w=min(maxx,ss-n);
printf("%lld\n",w);
}
}
}
int main()
{
solve();
}
不知道为什么,用pow就过不了下面贴上错误代码
#include<iostream>
#include<algorithm>
#include<cstring>
#include<map>
#include<cmath>
#include<queue>
#include<sstream>
#include<vector>
using namespace std;
#define ll long long
const ll inf=1e18;
int a[120000],n;
void solve()
{
ll s=0,ss=0;
cin>>n;
for(int i=0;i<n;i++)
{cin>>a[i];
ss+=a[i];}
sort(a,a+n);
if(n>=53)
printf("%lld\n",ss-n);
else
{
if(n==1||n==2)
printf("%d\n",a[0]-1);
else
{
ll maxx=inf,flag=1,oo=0;
for(ll i=2;i<=100000;i++)
{
ll q=0;
for(ll j=0;j<n;j++)
{
ll p=pow(i,j);
if(p>1e14)
{
flag=0;
break;
}
q+=abs(a[j]-p);
}
if(flag==0)break;
if(maxx>q)
{
oo=i;
maxx=q;
}
}
ll w=min(maxx,ss-n);
printf("%lld\n",w);
}
}
}
int main()
{
solve();
}