改成每次只加一格呢

👁️ 1 人浏览 💬 0 人评论 ❤️ 添加收藏

同样 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 编译。)

提交你的答案
请登录后提交答案。
去登录
代码编辑器
Ctrl + Enter 运行
本次输入:
输出:

                        
👩‍🏫
AI
💬 题目评论

全部评论