链接:http://codeforces.com/problemset/problem/558/C
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.
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.
题意:
给你若干个数。
对每个数都可以进行除或者乘的操作。 3/2=1
问 最少 多少步操作,可以让所有数字都相等。
做法:
首先如果都变成一个数字,那这个数字肯定是小于等于这些数字里的最大的那个的。
这里可以把每个数字看成二进制。
如
11(D)
1101(2)
所以其实可以枚举任意一个数。
任意一个二进制可以往左移若干位,得到一个新的数字。
出现奇数次数最多是log(n),向左移动最多也是log(n) 所以复杂度是log^2(n)*n
或者往右移。
可以知道如果奇数往右移时,二进制会少一个1,所以此时向左移会出现的数字都是之前没出现过的。
把每个出现的数字记录步数,记录出现次数,最后统计每个出现次数到达n的数字的最小步数和。
int ci[101000]; int buhe[101000]; int main() { int n; int lim=100000; while(scanf("%d",&n)!=EOF) { memset(ci,0,sizeof ci); memset(buhe,0,sizeof buhe); for(int i=0;i<n;i++) { int num; scanf("%d",&num); int flag=1; int bu=0; while(num) { if(flag) { int tt=bu+1; int num2=num*2;; while(num2<=lim) { ci[num2]++; buhe[num2]+=tt; num2*=2; tt++; } flag=0; } ci[num]++; buhe[num]+=bu; bu++; if(num%2==0) num/=2; else { flag=1; num/=2; } } } int minn=999999999; for(int i=1;i<=lim;i++) { if(ci[i]==n) minn=min(minn,buhe[i]); } printf("%d\n",minn); } return 0; }
版权声明:本文为博主原创文章,未经博主允许不得转载。
CF 558 C. Amr and Chemistry 暴力+二进制
原文地址:http://blog.csdn.net/u013532224/article/details/46910537