除2!
目錄
除2!
題目描述:
?編輯?題目解析:
代碼實現:
數組中兩個字符串的最小距離__牛客網
題目描述:
題目解析:
代碼實現:
除2!
題目描述:
給一個數組,一共有 n?n\ n?個數。
你能進行最多 k?k\ k?次操作。每次操作可以進行以下步驟:
- 選擇數組中的一個偶數 aia_iai?,將其變成 ai/2a_i/2ai?/2 。
現在你進行不超過 k?k\ k?次操作后,讓數組中所有數之和盡可能小。請輸出這個最小的和。
?題目解析:
? ? ? ? 不難想到,每次對最大的偶數除2即可,我們可以使用堆來獲取每次更新后最大的偶數。
代碼實現:
#include <iostream>
#include <queue>
using namespace std;long long Continuously_divide_by_2()
{priority_queue<int> q;int n, k;cin >> n >> k;long long ans = 0;for (int i = 0; i < n; i++){int t;cin >> t;ans += t;if (t % 2 == 0)q.push(t);}int m = 0;while (m < k && !q.empty()){int t = q.top();q.pop();t /= 2;ans -= t;if(t % 2 == 0)q.push(t);m++;}return ans;
}int main()
{cout << Continuously_divide_by_2() << endl;return 0;
}
?這里的結果需要用long long保存。
數組中兩個字符串的最小距離__牛客網
題目描述:
給定一個字符串數組strs,再給定兩個字符串str1和str2,返回在strs中str1和str2的最小距離,如果str1或str2為null,或不在strs中,返回-1。
?
題目解析:
- 這道題我們甚至不需要用一個字符串數組來保存這些字符串;
- 我們只需要一個pos變量來記錄最新出現的目標字符串的位置,和一個tmpstr變量來記錄出現的是哪個目標字符串(因為有兩個);
- 當出現的目標字符串于tmpstr不一樣的時候,就可以嘗試更新距離,只要出現目標字符串就更新pos。?
代碼實現:
#include <iostream>
using namespace std;int Minimum_distance() {int n = 0;string str1, str2, strs, strt;int pos = 0;cin >> n;cin >> str1 >> str2;int ans = n + 1;for (int i = 0; i < n; i++) {cin >> strs;if (strs == str1) {if (strt.empty() || strt == str1) {}else {ans = min(ans, i - pos);}pos = i;strt = str1;} else if (strs == str2) {if (strt.empty() || strt == str2) {}else {ans = min(ans, i - pos);}pos = i;strt = str2;}}if (ans == n + 1) return -1;else return ans;
}int main() {cout << Minimum_distance();return 0;
}