1103-木棒还原

Description
有N根木棒,现在要把N根木棒还原为一根并且每次只能将两根进行连接,所花费的时间是两根木棒的长度和,只有相邻的两根木棒可以连接,要求还原为一根木棒且总时间最短。
Input
输入数据由一个整数N打头( 1 <= N <= 100 ),表示N根木棒,接下来一行由N个数构成,中间用空格隔开,O1O2…ON( 1 <= Oi <= 100 )表示每根木棒的长度。
Output
输出一行正整数,表示还原为一根木棒的最短时间。
Sample Input
3 8 5 8
Sample Output
34
Source

#include<iostream>
#include<vector>
#include<cstdio>
using namespace std;

int main() {
    int n, tmp, result = 0;
    vector<int>num;
    cin >> n;
    for (int i = 0; i < n; i++) {
        scanf("%d", &tmp); 
        num.push_back(tmp);
    }
    while (num.size() != 1) {
        int min = 201, n = 0;
        for (int i = 0; i < num.size()-1; i++) {
            tmp = num[i] + num[i + 1];
            if (tmp < min)min = tmp, n = i;
        }
        result += min;
        num[n] = min;
        num.erase(num.begin() + n + 1);
    }
    cout << result;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
"粉粹木棒"(Crush the Stick)是一个经典的编程练习,通常用于教学或演示递归算法C++中的应用。这个练习中,你需要编写一个函数,计算一根木棒在一系列压力作用下最终断裂成零段的最小次数。木棒每受到一定的压力就会断成两段,直到无法再断为止。 以下是一个简单的C++代码示例,使用递归实现这个功能: ```cpp #include <iostream> using namespace std; int crushTheStick(int pressure, int currentLength) { // 基线条件:如果木棒长度为0,说明已经断成零段,返回0 if (currentLength == 0) { return 0; } // 递归条件:如果当前长度大于压力,表示木棒还能断,需要继续递归 else if (currentLength > pressure) { // 断一次,木棒长度减半,需要断裂次数加一 return 1 + crushTheStick(pressure, currentLength / 2); } // 如果木棒长度正好等于压力,意味着不需要进一步断裂 else { return crushTheStick(pressure, 0); // 木棒断裂后直接返回0 } } int main() { int pressure; // 输入压力值 cout << "Enter the pressure: "; cin >> pressure; int initialLength = 1000; // 或者其他初始木棒长度 int minBreaks = crushTheStick(pressure, initialLength); cout << "Minimum number of breaks needed to crush the stick: " << minBreaks << endl; return 0; } ``` 在这个代码中,`crushTheStick`函数接受压力值和当前木棒长度作为参数,然后据规则进行递归。用户可以在`main`函数中输入压力值,并调用该函数获取结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值