標籤:
預先處理兩個數組:
vis[x],有幾個數能夠變成x
num[x],所有數變成x最少需要變化的步數
ans=min(num[x]),vis[x]==n
#include<map>#include<string>#include<cstring>#include<cstdio>#include<cstdlib>#include<cmath>#include<queue>#include<vector>#include<iostream>#include<algorithm>#include<bitset>#include<climits>#include<list>#include<iomanip>#include<stack>#include<set>using namespace std;int num[int(1e5)+10],vis[int(1e5)+10];void work(int val){ int t=val*2,step=1; while(t<=int(1e5)) { vis[t]++; num[t]+=step; step++; t<<=1; } t=val,step=0; while(t>0) { vis[t]++; num[t]+=step; if((t&1)&&t>1) { int ts=step+2,tt=t/2*2; while(tt<=int(1e5)) { vis[tt]++; num[tt]+=ts; tt<<=1; ts++; } } step++; t>>=1; }}int main(){ int n; cin>>n; for(int i=0;i<n;i++) { int t; cin>>t; work(t); } int ans=INT_MAX; for(int i=1;i<=int(1e5);i++) if(vis[i]==n) ans=min(ans,num[i]); cout<<ans;}
time limit per test1 secondmemory limit per test256 megabytesinputstandard inputoutputstandard output
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?
Input
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
Output one integer the minimum number of operations required to make all the chemicals volumes equal.
Sample test(s)input
34 8 2
output
2
input
33 5 6
output
5
Note
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.
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
codeforces 558 C Amr and Chemistry