18.树的构造

这里可以考虑已知目标值为n,反向操作,怎么以最快的步骤把他减到0。
首先考虑能否被3整除,如果能够那就直接除3;
如果有余数,减完余数后继续去除3,这样的步骤将是最快的。

code:

#include <iostream>
using namespace std;
int main() {
    int n;
    cin >> n;
    // 记录需要的步骤次数
    int cnt = 0;
    while(n > 0){
        if(n % 3 == 0){
            n = n / 3;
            cnt++;
        }else if(n % 3 == 1){
            n = n - 1;
            cnt++;
        }else{
            n = n - 2;/*  */
            cnt +=2;
        }
    }
    cout << cnt << endl;
}
posted @ 2024-08-03 11:51  alone_qing  阅读(11)  评论(0)    收藏  举报