Codeforces Round #312 (Div. 2) C. Amr and Chemistry --------思维
Amr loves Chemistry, and specially doing experiments. He is preparing for a new interesting experiment.
Amr has n different types of chemicals. Each chemical i has an initial volume of ai liters. For this experiment, Amr has to mix all the chemicals together, but all the chemicals volumes must be equal first. So his task is to make all the chemicals volumes equal.
To do this, Amr can do two different kind of operations.
- Choose some chemical i and double its current volume so the new volume will be 2ai
- Choose some chemical i and divide its volume by two (integer division) so the new volume will be
Suppose that each chemical is contained in a vessel of infinite volume. Now Amr wonders what is the minimum number of operations required to make all the chemicals volumes equal?
The first line contains one number n (1 ≤ n ≤ 105), the number of chemicals.
The second line contains n space separated integers ai (1 ≤ ai ≤ 105), representing the initial volume of the i-th chemical in liters.
Output one integer the minimum number of operations required to make all the chemicals volumes equal.
3
4 8 2
2
3
3 5 6
5
In the first sample test, the optimal solution is to divide the second chemical volume by two, and multiply the third chemical volume by two to make all the volumes equal 4.
In the second sample test, the optimal solution is to divide the first chemical volume by two, and divide the second and the third chemical volumes by two twice to make all the volumes equal 1.
题意:
一些数,可以对它们进行两种操作,*2或者/2,问要把这些数变成同一个数最少需要几步。
分析:
首先最后变成的那个数一定是小于等于max(初始给出的数)。
然后应该是先除后乘得到最后的数。
我们现在先只考虑除,则可以用b[]记录利用已知数通过“/”运算能得到某个数的个数,c[]记录需要的步数。
如果b[i]==n说明是可以将所有数变成i的,可更新ans = min(ans,c[i])
但我们还没考虑乘,如果i%2==0 && b[i/2]==n也可满足
这时将所有数变成i,也可更新ans。这时c[i] = c[i/2]-b[i]+n-b[i]
其中c[i/2]-b[i]表示有b[i]个数是不需要先变到i/2再变回i的。所以从c[i/2]中减去b[i]。
有n-b[i]个数要从i/2变到i,i/2变到i是一次乘法操作,共n-b[i]步。
#include<cstdio> #include<cstring> #include<iostream> #include<algorithm> #include<cstdlib> #include<cmath> #include<vector> #include<queue> #include<map> #include<set> using namespace std; typedef long long ll; int b[1000010],c[1000010]; int a[100010]; int main() { int n,step; while(~scanf("%d",&n)) { memset(b,0,sizeof(b)); memset(c,0,sizeof(c)); int maxc = 0; for(int i=0;i<n;i++) { scanf("%d",&a[i]); if(a[i]>maxc) maxc = a[i]; b[a[i]]++; step = 0; while(a[i]>=1) { a[i]/=2; step++; b[a[i]]++; c[a[i]]+=step; } } int ans = c[1]; for(int i=2;i<=maxc;i++) { if(b[i]==n) { ans = min(ans,c[i]); } else if(i%2==0 && b[i/2]==n) { c[i] = c[i/2]-b[i]+n-b[i]; b[i] = n; ans = min(ans,c[i]); } } printf("%d\n",ans); } return 0; }