题意:长度为n的序列a,操作1:将某个a[i]*2.操作2:将某个a[i]/2(下取整).
n,a[i]<=1e5.问最少需要多少次操作能使得序列a的数都相同?
最后的数肯定不会超过序列中的最大值mx,
若y>mx 那么每个元素的最后一次操作肯定是*2=y>mx,此时去掉乘2操作,操作数减小,数列的数还是相等
操作每次都是乘以或者除以2[下取整]
19-10-5-2
19-10-20-40
19-10-5-2-4-8-...
除法由奇数变为偶数时,此时进行乘法能变到新的数.
也就是二进制最低位如果为1,那么此时/2后*2得到新的数和原来不同.
最大数的二进制位数为m,最坏情况下bit都为1,则最多生成m*(m+1)/2新的数(每次操作后都是前缀为11..开头的数).
标程:
n,a[i]<=1e5.问最少需要多少次操作能使得序列a的数都相同?
最后的数肯定不会超过序列中的最大值mx,
若y>mx 那么每个元素的最后一次操作肯定是*2=y>mx,此时去掉乘2操作,操作数减小,数列的数还是相等
操作每次都是乘以或者除以2[下取整]
19-10-5-2
19-10-20-40
19-10-5-2-4-8-...
除法由奇数变为偶数时,此时进行乘法能变到新的数.
也就是二进制最低位如果为1,那么此时/2后*2得到新的数和原来不同.
最大数的二进制位数为m,最坏情况下bit都为1,则最多生成m*(m+1)/2新的数(每次操作后都是前缀为11..开头的数).
计算f[i]:表示前k个数变成i的最小价值即可.O(n*m*(m+1)/2)
#include <bits/stdc++.h>
using namespace std;
const int N=3e5+5,inf=0x3f3f3f3f;
int n,a[N],f[N],h[N];
void calc(int x,int cnt)
{
int mx=3e5;
while(x<=mx)
{
f[x]+=cnt,h[x]++;
x*=2;
cnt++;
}
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
// freopen("1.txt","r",stdin);
memset(f,0,sizeof(f));
cin>>n;
for(int i=1;i<=n;i++)
cin>>a[i];
for(int i=1;i<=n;i++)
{
h[a[i]]++;
calc(a[i]*2,1);
int cnt=1,num;
while(a[i])
{
if(a[i]!=1&&a[i]%2)
calc(a[i]/2*2,cnt+1);
a[i]/=2;
f[a[i]]+=cnt,h[a[i]]++;
cnt++;
}
}
int res=inf;
for(int i=1;i<N;i++)
if(h[i]==n)
res=min(res,f[i]);
cout<<res<<'\n';
return 0;
}
标程:
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <string>
#include <cctype>
#include <stack>
#include <queue>
#include <vector>
#include <map>
#include <sstream>
#include <cmath>
#include <limits>
#include <utility>
#include <iomanip>
#include <set>
#include <numeric>
#include <cassert>
#include <ctime>
#define INF_MAX 2147483647
#define INF_MIN -2147483647
#define INF_LL 9223372036854775807LL
#define INF 2000000000
#define PI acos(-1.0)
#define EPS 1e-8
#define LL long long
#define mod 1000000007
#define pb push_back
#define mp make_pair
#define f first
#define s second
#define setzero(a) memset(a,0,sizeof(a))
#define setdp(a) memset(a,-1,sizeof(a))
#define bits(a) __builtin_popcount(a)
using namespace std;
int cnt[100005], vis[100005], steps[100005];
int main()
{
//ios_base::sync_with_stdio(0);
//freopen("lca.in", "r", stdin);
//freopen("lca.out", "w", stdout);
int n, res = INF, x, y;
scanf("%d", &n);
for(int i=1;i<=n;i++)
{
scanf("%d", &x);
queue<pair<int, int> > q;
q.push(mp(x, 0));
while(!q.empty())
{
x = q.front().f;
y = q.front().s;
q.pop();
if(x > 100003) continue;
if(vis[x] == i) continue;
vis[x] = i;
steps[x]+=y;
cnt[x]++;
q.push(mp(x * 2, y + 1));
q.push(mp(x / 2, y + 1));
}
}
for(int i=0;i<=100000;i++)
if(cnt[i] == n)
if(res > steps[i])
res = steps[i];
printf("%d", res);
return 0;
}