C语言程序设计基础|部分和问题

题目描述:

给定整数a1、a2、.......an,判断是否可以从中选出若干数,使它们的和恰好为k。

输入要求:

有多组测试数据。每组测试数据两行:

第一行:正整数n、整数k,n表示数的个数,k表示数的和。

第二行:n个数

输出要求:

每组测试数据,如果和恰好可以为k,输出“YES”,并按输入顺序依次输出是由哪几个数的和组成,否则“NO”

#include<iostream>
#include<cmath>
#include<iomanip>
#include<algorithm>
#include<cstring>
using namespace std;
int isadd[1000];
int partsum(int arr[], int k, int n)
{
    int times = pow(2, n);
    for (int i = times - 1; i >= 0; i--)//利用二进制的特性,找出所有排列的可能性
    {
        int number = i, count = 0, place = 0, sum = 0;
        while (number)
        {
            if (number % 2)
            {
                sum += arr[place];
                isadd[count] = arr[place];
                count++;
            }
            if (sum == k)
            {
                return count;
            }
            number /= 2;
            place++;
        }
    }
    return 0;
}
int main() {
    int n, k;
    while (cin >> n >> k)
    {
        int arr[n], count;
        for (int i = 0; i < n; i++)
        {
            cin >> arr[i];
        }
        count = partsum(arr, k, n);
        if (count)
        {
            cout << "YES" << endl;
            for (int i = 0; i < count; i++)
            {
                if ((i != count - 1) && isadd[i] != 0)
                {
                    cout << isadd[i] << " ";
                }
                else if ((i == count - 1) && isadd[i] != 0)
                {
                    cout << isadd[i];
                }
            }
            cout << endl;
        }
        else
        {
            cout << "NO" << endl;
        }
    }
    return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

再给艾克三年

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值