改成每次只加一格呢
同样 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, inc1).first << endl;
}
(本题用 g++ -std=c++17 -O0 编译。)
全部评论