容量翻倍十六次搬多少
从容量 1 开始,满了就翻倍。做 16 次 push_back,一共搬动了多少个元素?
#include <algorithm>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
int dbl(int c) { return c * 2; }
int inc1(int c) { return c + 1; }
// 模拟 n 次 push_back:返回 {一共搬了多少个元素, 单次最多搬几个}
pair<int, int> moves(int n, int (*grow)(int)) {
int cap = 1, size = 0, total = 0, worst = 0;
for (int k = 0; k < n; k++) {
if (size == cap) {
total += size;
worst = max(worst, size);
cap = grow(cap);
}
size++;
}
return {total, worst};
}
int main() {
cout << moves(16, dbl).first << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论