【CodeForces - 558C】Amr and Chemistry(位运算,bfs,计数,思维,tricks)
題干:
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?ailiters. 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.
Examples
Input
3 4 8 2Output
2Input
3 3 5 6Output
5Note
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.
題目大意:
給你n個整數,每一個整數可以進行兩種操作,除2(取整)或者乘2.每個整數可以進行任意次這樣的操作。
使這n個整數都變為相同的整數最少需要多少次操作。
解題報告:
? ? bfs考慮每一個數可以到達的地方以及他可以該地方的所有的步數。注意一個細節就是每次bfs不要都清空vis,可能會超時,因為肯定memset了很多本來就是0的值,可以選擇vis[i]=i來判斷是否走過。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define ll long long #define pb push_back #define pm make_pair using namespace std; const int MAX = 2e5 + 5; const int INF = 0x3f3f3f3f; int cnt[MAX], vis[MAX], steps[MAX]; int main() {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(pm(x, 0));while(!q.empty()) {x = q.front().first;y = q.front().second;q.pop();if(x > 100003) continue;if(vis[x] == i) continue;vis[x] = i;steps[x]+=y;cnt[x]++;q.push(pm(x * 2, y + 1));q.push(pm(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; }?
總結
以上是生活随笔為你收集整理的【CodeForces - 558C】Amr and Chemistry(位运算,bfs,计数,思维,tricks)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: AMD Yes!FSR 2.0插件已适用
- 下一篇: 【HDU - 3394】Railway(