c语言刷题 数组——困难

题目:满足特异条件的数列。输入m和n(20≥m≥n≥0),求出满足以下方程式的正整数数列i1,i2,…,in,使得i1+i2+…+in=m,且i1≥i2≥…≥in。例如:
当n=4,m=8时,将得到如下5个数列:
5 1 1 1 4 2 1 1 3 3 1 1 3 2 2 1 2 2 2 2
**输入格式要求:“%d” 提示信息:“Please enter requried terms (<=10):”
" their sum:"
**输出格式要求:“There are following possible series:\n” “[%d]:” “%d”
程序运行示例1:
Please enter requried terms (<=10): 4 8
their sum:There are following possible series:
[1]:5111
[2]:4211
[3]:3311
[4]:3221
[5]:2222
程序运行示例2:
Please enter requried terms (<=10):4 10
their sum:There are following possible series:
[1]:7 1 1 1
[2]:6 2 1 1
[3]:5 3 1 1
[4]:4 4 1 1
[5]:5 2 2 1
[6]:4 3 2 1
[7]:3 3 3 1
[8]:4 2 2 2
[9]:3 3 2 2

代码:

#include<stdio.h>
#define NUM 10
int i[NUM];
int main()
{
    int sum, n, total, k, flag, count = 0;
    printf("Please enter requried terms(<=10):");
    scanf("%d", &n);
    printf("                             their sum:");
    scanf("%d", &total);
    sum = 0;
    k = n;
    i[n] = 1;
    printf("There are following possible series:\n");
    while (1)
    {
        if (sum + i[k] < total)
        {
            if (k <= 1)
            {
                i[1] = total - sum;
                flag = 1;
            }
            else
            {
                sum = sum + i[k];
                k--;
                i[k] = i[k + 1];
                continue;
            }
        }
        else if (sum + i[k] > total || k != 1)
        {
            sum -= i[++k];
            flag = 0;
        }
        else
            flag = 1;
        if (flag)
        {
            printf("[%d]:", ++count);
            for (flag = 1; flag <= n; ++flag)
                printf("%d", i[flag]);
            printf("\n");
        }
        if (++k > n)
            break;
        sum -= i[k];
        i[k]++;
    }
    return 0;
}

`

  • 4
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值