大佬教程收集整理的这篇文章主要介绍了将 X 项按 N 种方式平均分配,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我想知道是否有人可以深入了解一种算法,该算法可以将给定数量的项目(例如 x)划分为 n 个不同的组。
例如。
# 项 | # 组 | 分组 |
---|---|---|
5 | 2 | Group1 为 3,Group2 为 2 |
5 | 3 | Group1 为 2,Group2 为 2,Group3 为 1 |
8 | 7 | Group1 为 2,Groups2-7 为 1 |
10 | 2 | Group1 为 5,Group2 为 5 |
对于 x 项数和 n 组数的值实际上没有限制。例如,一个可能是数千,另一个可能是 87。
我找了一段时间,没有找到任何东西。发完后又搜索了一下,马上就找到了(笑)。
#include<bits/stdc++.h>
using namespace std;;
// Function that prints
// the required sequence
void split(int x,int n)
{
// If we cAnnot split the
// number into exactly 'N' parts
if(x < n)
cout<<"-1"<<" ";
// If x % n == 0 then the minimum
// difference is 0 and all
// numbers are x / n
else if (x % n == 0)
{
for(int i=0;i<n;i++)
cout<<(x/n)<<" ";
}
else
{
// upto n-(x % n) the values
// will be x / n
// after that the values
// will be x / n + 1
int zp = n - (x % n);
int pp = x/n;
for(int i=0;i<n;i++)
{
if(i>= zp)
cout<<(pp + 1)<<" ";
else
cout<<pp<<" ";
}
}
}
// Driver code
int main()
{
int x = 5;
int n = 3;
split(x,n);
}
来源:Geeks for Geeks:将数字分成 N 个部分,使得最小和最大部分之间的差异最小。 链接:https://www.geeksforgeeks.org/split-the-number-into-n-parts-such-that-difference-between-the-smallest-and-the-largest-part-is-minimum/
以上是大佬教程为你收集整理的将 X 项按 N 种方式平均分配全部内容,希望文章能够帮你解决将 X 项按 N 种方式平均分配所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。