CodeForces 558C Amr and Chemistry (bitwise operation, number theory, rule, enumeration), codeforces558c
Codeforces 558C
Question: give n numbers. You can perform two operations on each number: num * 2 and num/2 (rounded down: the minimum number of operations required to make n equal.
Analysis:
Calculates the binary common prefix of each number.
The enumeration method is also supported.
/**Author : Flint_x *Created Time : 2015-07-22 12:33:11 *File name : whust2_L.cpp */#include<iostream>#include<sstream>#include<fstream>#include<vector>#include<list>#include<deque>#include<queue>#include<stack>#include<map>#include<set>#include<bitset>#include<algorithm>#include<cstdio>#include<cstdlib>#include<cstring>#include<cctype>#include<cmath>#include<ctime>#include<iomanip>#define inf 2139062143using namespace std;const double eps(1e-8);typedef long long lint;#define cls(a) memset(a,0,sizeof(a))#define rise(i,a,b) for(int i = a ; i <= b ; i++)#define fall(i,a,b) for(int i = a ; i >= b ; i--)const int maxn = 100000 + 5;int num[maxn];int temp[maxn];int odd[maxn],cnt[maxn];int n;int main(){ // freopen("input.txt","r",stdin);// freopen("output.txt","w",stdout);while(cin >> n){for(int i = 1 ; i <= n ; i++){scanf("%d",&num[i]);}cls(cnt);cls(odd);sort(num+1,num+n+1);for(int i = 1 ; i <= n ; i++) temp[i] = num[i];int t = num[1];for(int i = 1 ; i <= n ; i++){while(t ^ num[i]){if (t < num[i]) num[i] >>= 1;else t >>= 1;}}for(int i = 1 ; i <= n ; i++) num[i] = temp[i];for(int i = 1 ; i <= n ; i++){while (num[i] ^ t){cnt[i]--;if(num[i] % 2) odd[i] = cnt[i];num[i] >>= 1;}}lint ans = inf;for(int i = 0 ; i < 20 ; i++){lint x = 0;for(int j = 1 ; j <= n ; j++){if (odd[j] == 0 || cnt[j] + i <= odd[j]) x += abs(cnt[j] + i);else x += abs(odd[j]) + abs(odd[j] - (cnt[j] + i));}//cout << x << endl;ans = min(ans,x);}cout << ans << endl;} return 0;}
Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.