【牛客】[编程题] 幸运的袋子C++

1.题目描述

链接https://www.nowcoder.com/questionTerminal/a5190a7c3ec045ce9273beebdfe029ee?toCommentId=213624

一个袋子里面有n个球,每个球上面都有一个号码(拥有相同号码的球是无区别的)。如果一个袋子是幸运的当且仅当所有球的号码的和大于所有球的号码的积。
例如:如果袋子里面的球的号码是{1, 1, 2, 3},这个袋子就是幸运的,因为1 + 1 + 2 + 3 > 1 * 1 * 2 * 3
你可以适当从袋子里移除一些球(可以移除0个,但是别移除完),要使移除后的袋子是幸运的。现在让你编程计算一下你可以获得的多少种不同的幸运的袋子。

2.思路分析

  1. 主函数中先输入数据,在排序
  2. 然后调用函数Count来计数个数,最后销毁x
  3. Count这个函数是一个递归函数
  4. 只要满足幸运的袋子,那就继续递归
  5. 不满足的话,那就去掉不满足的
  6. 在去掉1 那部分的影响

3.代码实现

#include <iostream>
#include <algorithm>
using namespace std;

// 袋子里面数字的个数
int n = 0;
int* x = NULL;

int Count(int pos, int add, long long mul)
{
    int num = 0;
    for(int i = pos; i < n; i++)
    {
        add += x[i];
        mul *= x[i];
        
        // 判定其是不是幸运的袋子
        if(add > mul)
            num += 1 + Count(i + 1, add, mul);
        else if(x[i] == 1)
            num += Count(i + 1, add, mul);
        else
            break;
        
        // 不符合的话直接去掉
        add -= x[i];
        mul /= x[i];
        
        // 去掉x[i]是1 的情况
        while(x[i] == x[i + 1] && (i + 1 <n))
             i++;
    }
    return num;
}


int main()
{
    cin >> n;
    // 开辟空间
    x = new int[n];
    int add = 0; // 和
    long long mul = 1; // 积
    // 输入数据
    for(int i = 0; i < n; i++)
        cin >> x[i];
    
    // 排序,记得头文件
    sort(x, x + n);
    // 计数函数
    int num = Count(0, add, mul);
    // 打印
    cout << num;
    // 销毁
    if(x != NULL)
    {
        delete []x;
        x = NULL;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43967449/article/details/106796040