课时4作业3

Description

某人想将手中的一张面值100元的人民币换成10元、5元、2元和1元面值的票子。要求换正好40张,且每种票子至少一张。问:有几种换法?

Input

无输入

Output

一个数,表示共有多少种换法

Sample Input 1

Sample Output 1

不能告知,因为只有一个数,偷偷告诉你小于100

方法一:四重循环遍历
时间复杂度: O ( n 4 ) O(n^4) O(n4)

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int N = 1e5 + 10;
int a[N];

void solve() {
    // 100 -> 10、5、2、1

    int res = 0;
    for (int i = 1; i <= 40; i ++ ) {
        for (int j = 1; j <= 40; j ++ ) {
            for (int k = 1; k <= 40; k ++ ) {
                for (int l = 1; l <= 40; l ++ ) {
                    int sum = 10 * i + 5 * j + 2 * k + l;
                    int num = i + j + k + l;
                    if (sum == 100 && num == 40) {
                        res ++ ;
                    }
                }
            }
        }
    }
    cout << res << "\n";
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    int _ = 1;
//    cin >> _;
    while (_ -- ) {
        solve();
    }
    return 0;
}

方法一:四重循环遍历
时间复杂度: O ( n 3 ) O(n^3) O(n3)

#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
typedef pair<int, int> PII;
const int N = 1e5 + 10;
int a[N];

void solve() {
    // 100 -> 10、5、2、1

    int res = 0;
    for (int i = 1; i <= 40; i ++ ) {
        for (int j = 1; j <= 40; j ++ ) {
            for (int k = 1; k <= 40; k ++ ) {
                int sum = i * 10 + j * 5 + k * 2;
                int dif = 100 - sum;
                if (dif >= 1 && i + j + k + dif == 40) {
                    res ++ ;
//                    cout << i << " " << j << " " << k << " " << dif << "\n";
                }
            }
        }
    }
    cout << res << "\n";
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    int _ = 1;
//    cin >> _;
    while (_ -- ) {
        solve();
    }
    return 0;
}

把1直接算出来而不是用循环遍历,可以省掉一重循环,将时间复杂度变成 O ( n 3 ) O(n^3) O(n3)

在这里插入图片描述
错了四遍的神奇题目,因为把题目的每种票子至少一张看漏了,要好好审题,不然罚时嘎嘎多!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值